在python etree中使用XPATH选择没有特定属性的节点 [英] Using XPATH in python etree to select node with out a specific attribute
问题描述
以下是我的xml文件内容,
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>
以下是我的代码,
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。查找(自身,路径,名称空间)
文件 C:\Python27\lib\xml\etree\ElementPath.py,行285,在查找
中返回iterfind(elem,path ,名称空间).next()
文件 C:\Python27\lib\xml\etree\ElementPath.py,第263行,位于
选择器中。append(ops [token [0]](下一个令牌))
文件 C:\Python27\lib\xml\etree\ElementPath.py,行224,在prepare_predicate
中引发SyntaxError(谓词无效)
SyntaxError:inval id谓词
推荐答案
ElementTree仅支持XPath 1.0的子集。请参见 https://docs.python.org/2/ library / xml.etree.elementtree.html#xpath-support 。 not()
或 count()
之类的功能不起作用。
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.
这里是不使用XPath即可选择不具有 direction
属性的 neighbor
元素的方法:
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
这篇关于在python etree中使用XPATH选择没有特定属性的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!