text1 text2

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 ([) 
+4
source share
4 answers

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.

+3
source

This XPath will select the nodes of the bar whose key attribute is false :

 /foo/bar[@key='false'] 

If the current context of the node is foo node, then this will also work:

 ./bar[@key='false'] 
+2
source

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 .

+1
source

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.

0
source

Source: https://habr.com/ru/post/1333941/


All Articles