以下是我的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
我收到以下错误,
文件“C:\Python27\lib\xml\etree\ElementTree.py”,第 363 行,在查找中
返回 ElementPath.find( self ,路径,命名空间)
文件“C:\Python27\lib\xml\etree\ElementPath.py”,第 285 行,在查找中
返回 iterfind(元素,路径,命名空间).next()
文件“C:\Python27\lib\xml\etree\ElementPath.py”,第 263 行,在 iterfind 中
selector.append(ops[token[0]](next, token))
文件“C:\Python27\lib\xml\etree\ElementPath.py”,第 224 行,在 prepare_predicate 中
raise SyntaxError("无效谓词")
语法错误:谓词无效
最佳答案
ElementTree 仅支持 XPath 1.0 的一个子集。参见 https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support . not()
或 count()
等函数不起作用。
下面是如何在不使用 XPath 的情况下选择没有 direction
属性的 neighbor
元素:
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
关于python - 在 python etree 中使用 XPATH 选择没有特定属性的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26653792/