0

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 Answer 1

2

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>]
Sign up to request clarification or add additional context in comments.

1 Comment

Can I add more than one attributes also to this like [@name="node3" @value="value3"]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.