How can I get element from XML file with attribute having specific value

我怕爱的太早我们不能终老 提交于 2019-12-08 13:46:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!