繁体   English   中英

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

[英]Using XPATH in python etree to select node with out a specific attribute

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

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
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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM