Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementTree XPath - Select Element based on attribute

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 ([) 
like image 899
Nick Stinemates Avatar asked Oct 21 '08 15:10

Nick Stinemates


People also ask

What is XML etree ElementTree?

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.

How to parse XML in Python ElementTree?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.

Which Python library is used to transform XML data structure into Element tree structure?

ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with.


1 Answers

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.

like image 106
Florian Bösch Avatar answered Oct 02 '22 12:10

Florian Bösch