Get attribute names and values from ElementTree

Igal picture Igal · Jan 14, 2013 · Viewed 28.6k times · Source

I have an XML <root> element with several attributes. I've been using the ElementTree package.

After I've parsed a tree from an xml file, I'm getting the document root, but I want to get the requested attribute, or even the entire list of attributes.

<root a="1" b="2" c="3">
    </blablabla>
</root>

How can I retrieve all attribute names and values for a <root> element with ElementTree?

Answer

Martijn Pieters picture Martijn Pieters · Jan 14, 2013

Each Element has an attribute .attrib that is a dictionary; simply use it's mapping methods to ask it for it's keys or values:

for name, value in root.attrib.items():
    print '{0}="{1}"'.format(name, value)

or

for name in root.attrib:
    print '{0}="{1}"'.format(name, root.attrib[name])

or use .values() or any of the other methods available on a python dict.

To get an individual attribute, use the standard subscription syntax:

print root.attrib['a']