How to select data for xml Element with specific attribute value?
Solution 1
I might be wrong but I dont think that the "./bar[@key='false']
" notation works in Python 2.5.5 (or at least not with the ElementTree that comes with it). I have observed the same problem in Python 2.6.5, but it does work in Python 2.7.1. I guess you will have to use another library or try the "experimental" GAE with Python 2.7.
Solution 2
This XPath will select the bar
nodes whose key
attribute is equal to false
:
/foo/bar[@key='false']
If the current context node is the foo
node then this will also work:
./bar[@key='false']
Solution 3
Based on the answer here, the XPath selector functionality was not implemented in ElementTree until version 1.3, which ships with Python 2.7, as @cdemers said.
Will Curran
Updated on June 04, 2022Comments
-
Will Curran almost 2 years
Given:
<foo> <bar key="true">text1</bar> <bar key="false">text2</bar> <bar key="true">text3</bar> <bar key="true">text4</bar> </foo>
I want to get the text for the bar element where the key attribute = "false".
My application is Python 2.5.5 on GAE. The XML is not true xml, but I can load it as an ElementTree and fetch data normally.
Code example:
result = urllib2.urlopen(url).read() xml = ElementTree.fromstring(result) str = xml.find("./bar").attrib['key']
to get the first value. I've tried various xpath queries that I think should work but I've obviously got the syntax wrong.
UPDATE:
str = xml.findtext("./bar[@key='false']")
Throws error:
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/etree/ElementPath.py", line 93, in __init__ "expected path separator (%s)" % (op or tag) SyntaxError: expected path separator ([)