【问题标题】:Python ElementTree "Invalid descendant" errorPython ElementTree“无效后代”错误
【发布时间】:2016-11-14 05:21:00
【问题描述】:

我有一个 XML 文件,foo.xml:

<foo>
    <bar>
        <baz phrase="hello"/>
    </bar>
    <quux phrase="goodbye"/>
</foo>

我正在用这个 Python 代码解析它:

import lxml.etree as ET
# or if you don't have lxml: import xml.etree.ElementTree as ET

doc = ET.parse('foo.xml').getroot()

for elem in doc.findall('*[@phrase]'):
    print(elem)

这给了我:

<Element 'quux' at 0x7fa1419a1d18>

现在我想找到所有具有phrase 属性的元素,所以我尝试了'.//[@phrase]',但随后findall() 失败了:

SyntaxError: invalid descendant

我不明白出了什么问题。如果我使用内置的xml.etree.ElementTree 而不是lxml,则会出现相同的错误消息。

请注意,'.//' 有效,但返回 bar, baz, quux,我不想要 bar,因为它没有 phrase 属性。

【问题讨论】:

  • 你需要* in .//*[@phrase]
  • @furas 这应该是一个答案

标签: python xml elementtree


【解决方案1】:

您需要* 作为".//*[@phrase]" 中的标签名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 2014-08-08
    相关资源
    最近更新 更多