问题
XML file:
<Node name="node1">
<Node name="node2">
<Node name="node3">
<Node name="node4">
...
</Node>
</Node>
</Node>
</Node>
How to select or get "Node" object with "name" attribute having value as "node3" (or any specific value)?
Currently I am using xml.etree.ElementTree
from xml.etree import ElementTree
document = ElementTree.parse( 'filename.xml' )
nodes = document.find( 'Node')
for node in nodes:
if node.attribute('name') == "node3":
print("found")
break
Is there better way to avoid for loop? I am fine with other XML parser modules as well.
I am using python 2.7
回答1:
With lxml you can use XPath:
In [1]: from lxml.etree import parse
In [2]: tree = parse('nodes.xml')
In [3]: tree.xpath('//Node[@name="node3"]')
Out[3]: [<Element Node at 0x180ec30>]
With multiple predicates:
In [4]: tree.xpath('//Node[@name="node3"][@value="value3"]')
Out[4]: [<Element Node at 0x155d1e0>]
来源:https://stackoverflow.com/questions/20141939/how-can-i-get-element-from-xml-file-with-attribute-having-specific-value