Following is my xml file contents,
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" distance="500"/>
<neighbor name="Switzerland" direction="W"/>
</country>
</data>
Following is my code,
tree = ET.parse(fileName)
doc = tree.getroot()
#nodes = doc.findall(".//country/neighbor") #works
#nodes = doc.findall(".//country/neighbor[@direction]") #works
nodes = doc.findall(".//country/neighbor[not(@direction)]") #not working
I am getting the following error,
File "C:\\Python27\\lib\\xml\\etree\\ElementTree.py", line 363, in find return ElementPath.find(self, path, namespaces) File "C:\\Python27\\lib\\xml\\etree\\ElementPath.py", line 285, in find return iterfind(elem, path, namespaces).next() File "C:\\Python27\\lib\\xml\\etree\\ElementPath.py", line 263, in iterfind selector.append(ops[token[0]](next, token)) File "C:\\Python27\\lib\\xml\\etree\\ElementPath.py", line 224, in prepare_predicate raise SyntaxError("invalid predicate") SyntaxError: invalid predicate
ElementTree only supports a subset of XPath 1.0. See https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support . Functions such as not()
or count()
do not work.
Here is how you can select neighbor
elements that don't have a direction
attribute without using XPath:
tree = ET.parse(fileName)
for n in tree.iter('neighbor'):
if not(n.get('direction')): # If the element has no 'direction' attribute...
print n.get('name') # then print the value of the 'name' attribute
import xml.etree.ElementTree as etree
xmlD = etree.parse('xmlTest.xml')
root = xmlD.getroot()
for child in root:
for children in child:
print(children.text)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.