ElementTree XPath - Select Element based on attribute

Nick Stinemates picture Nick Stinemates · Oct 21, 2008 · Viewed 41.9k times · Source

I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the Documentation

Here's some sample code

XML

<root>
 <target name="1">
    <a></a>
    <b></b>
 </target>
 <target name="2">
    <a></a>
    <b></b>
 </target>
</root>

Python

def parse(document):
    root = et.parse(document)
    for target in root.findall("//target[@name='a']"):
        print target._children

I am receiving the following Exception:

expected path separator ([)

Answer

Florian B&#246;sch picture Florian Bösch · Oct 21, 2008

The syntax you're trying to use is new in ElementTree 1.3.

Such version is shipped with Python 2.7 or higher. If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.