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

标签 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

我收到以下错误,

文件“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/

相关文章:

javascript - 在 ajax 调用后为 jquery 每个函数添加延迟

xpath - 使用 cssSelector 获取子元素

html - 如何使用 XPath 获取 header 中的内容

python - Flask url_for 停止接受两位数的用户 ID。漏洞?

python - 从单词列表中创建句子 x 次

python - 类型错误 : can only concatenate tuple (not "vector") to tuple

java - 如何创建 LayoutInflater?

python - 通过哪种适应时间序列的技术可以替换 Python 中的 Keras MLP 回归模型中的交叉验证

php - 用 PHP 解析 XML CDATA

xml - 如何使用 xsl 合并多个 xml 文件?