How do I extract value of XML attribute in Python?

Using ElementTree you can use find method & attrib .

Example:

import xml.etree.ElementTree as ET

z = """<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>"""


treeOne = ET.fromstring(z)
print treeOne.find('./child').attrib['type']
print treeOne.find('./adult').attrib['type']

Output:

smallHuman
largeHuman

To get the attribute value from an XML, you can do like this:

import xml.etree.ElementTree as ET

xml_data = """<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>"""

# This is like ET.parse(), but for strings
root = ET.fromstring(xml_data)

for a child in root:
    print(child.tag, child.attrib)

You can find more details and examples on the link below: https://docs.python.org/3.5/library/xml.etree.elementtree.html

Tags:

Python

Xml