[英]Python ElementTree “Invalid descendant” error
I have an XML file, foo.xml
: 我有一个XML文件,
foo.xml
:
<foo>
<bar>
<baz phrase="hello"/>
</bar>
<quux phrase="goodbye"/>
</foo>
I'm parsing it with this Python code: 我用这个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)
That gives me: 这给了我:
<Element 'quux' at 0x7fa1419a1d18>
Now I want to find all elements with a phrase
attribute, so I tried './/[@phrase]'
but then findall()
fails: 现在我想找到带有
phrase
属性的所有元素,所以我尝试'.//[@phrase]'
但是然后findall()
失败了:
SyntaxError: invalid descendant
I don't understand what's wrong. 我不明白什么是错的。 The same error message appears if I use the built-in
xml.etree.ElementTree
instead of lxml
. 如果我使用内置的
xml.etree.ElementTree
而不是lxml
则会出现相同的错误消息。
Note that './/'
works, but returns bar, baz, quux
and I don't want bar
because it doesn't have a phrase
attribute. 请注意
'.//'
有效,但返回bar, baz, quux
,我不想要bar
因为它没有phrase
属性。
你需要*
作为".//*[@phrase]"
标签名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.