Get attribute names and values from ElementTree
Asked Answered
H

3

11

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?

Halford answered 14/1, 2013 at 17:18 Comment(0)
B
35

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']
Brade answered 14/1, 2013 at 17:21 Comment(0)
S
9

The attrib attribute of an ElementTree element (like the root returned by getroot) is a dictionary. So you can do, for example:

from xml.etree import ElementTree
tree = ElementTree.parse('test.xml')
root = tree.getroot()
print root.attrib

which will output, for your example

{'a': '1', 'b': '2', 'c': '3'}
Semiporcelain answered 14/1, 2013 at 17:26 Comment(0)
C
3

Some nice loop you can use it will get for each element of the xmlObject it's tag, text and attribute it will work for 2 levels XML, it's not the best way to iterate but it can be useful for simple things...

for headTag in xmlObject.getchildren():
    print headTag.tag, headTag.text, headTag.attrib
    for bodyTag in headTag.getchildren():
        print "\t", bodyTag.tag, bodyTag.text, bodyTag.attrib
Coverlet answered 23/9, 2013 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.