【发布时间】:2014-02-05 17:42:30
【问题描述】:
我正在尝试从命令行参数读取 XML 文件。我一般是使用 libxml2 和 XPath 的新手。我想使用 XPath 进行查询。
XML:
<?xml version="1.0"?>
<xmi:XMI xmlns:cas="http:///text/cas.ecore" xmlns:audioform="http:something" xmlns:xmi="http://blahblah" xmlns:lib="http://blahblah" xmlns:solr="http:blahblah" xmlns:tcas="http:///blah" xmi:version="2.0">
<cas:NULL xmi:id="0"/>
<cas:Sofa xmi:id="9" Num="1" ID="First" Type="text" String="play a song"/>
<cas:Sofa xmi:id="63" Num="2" ID="Second" Type="text" String="Find a contact"/>
<cas:Sofa xmi:id="72" Num="3" ID="Third" Type="text" String="Send a message"/>
<lib:Confidence xmi:id="1" sofa="9" begin="0" end="1" key="context" value="" confidence="1.0"/>
</xmi:XMI>
代码:
def main(argv):
try:
xmlfile=argv[0]
doc=libxml2.parseFile(xmlfile)
root2=doc.children
print root2 # This prints everything but <?xml version="1.0"?>
result= root2.xpathEval("//*")
for node in result:
print node
print node.nodePath(), node.name, node.content
我想更进一步,使用这个文件做一些处理。
- 如何使用 xpath 获得像 63 这样的值?来自
xmi:id="63"。 - 在
xmi:id = "72"处查找字符串。结果应该是“发送消息” - 在
xmi:id = 72 and ID= "Third"处查找字符串。结果应该是“发送消息” -
我尝试为此节点使用
node.Path()、node.name和node.content:<cas:Sofa xmi:id="9" Num="1" ID="First" Type="text" String="play a song"/>结果是:
/xmi:XMI/cas:Sofa[1]为nodePath(),沙发为名称且不打印任何内容
如何获得 1 和 2 和 3?
【问题讨论】:
标签: python xml text xpath libxml2