在python etree中使用XPATH来选择没有特定属性的节点

时间:2014-10-30 13:06:14

标签: python xml xpath elementtree

以下是我的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

2 个答案:

答案 0 :(得分:1)

ElementTree仅支持XPath 1.0的子集。见https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-supportnot()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)