以下是我的xml文件内容,
<?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>
以下是我的代码,
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
我收到以下错误,
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
答案 0 :(得分:1)
ElementTree仅支持XPath 1.0的子集。见https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support。 not()
或count()
等功能不起作用。
以下是如何在不使用XPath的情况下选择没有neighbor
属性的direction
个元素:
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
答案 1 :(得分:-2)
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)