簡體   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