Will Curran Will Curran - 4 months ago 11
Python Question

How to extract xml attribute using Python ElementTree

For:

<foo>
<bar key="value">text</bar>
</foo>


How do I get "value"?

xml.findtext("./bar[@key]")


Throws an error.

Answer
In [52]: import xml.etree.ElementTree as ET

In [53]: xml=ET.fromstring(contents)

In [54]: xml.find('./bar').attrib['key']
Out[54]: 'value'
Comments