简体   繁体   中英

Python ElementTree “Invalid descendant” error

I have an XML file, foo.xml :

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

I'm parsing it with this Python code:

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:

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 .

Note that './/' works, but returns bar, baz, quux and I don't want bar because it doesn't have a phrase attribute.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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