How to select data for an xml element with a specific attribute value?
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. XML is not true xml, but I can load it as an ElementTree and receive the 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 tried various xpath requests, which I think should work, but I clearly didn't understand the syntax.
UPDATE:
str = xml.findtext("./bar[@key='false']") Gives an error message:
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 ([) Maybe I'm wrong, but I donβt think that the notation " ./bar[@key='false'] " works in Python 2.5.5 (or at least not with ElementTree, which comes with it). I observed the same problem in Python 2.6.5, but it works in Python 2.7.1. I think you will have to use another library or try the βexperimentalβ GAE with Python 2.7.
The "[@attrib]" you are using is introduced only in ElementTree 1.3: http://effbot.org/zone/element-xpath.htm
which was introduced only for Python 2.7:
https://docs.python.org/2/library/xml.etree.elementtree.html
As mentioned above, you need to get this attribute differently or upgrade Python to run this code.