Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attribute names and values from ElementTree

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?

like image 285
Igal Avatar asked Jan 14 '13 17:01

Igal


People also ask

How do you parse an XML string in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.

How do you read a specific tag in an XML file in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

What is XML Etree ElementTree in Python?

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.


2 Answers

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']
like image 186
Martijn Pieters Avatar answered Sep 22 '22 23:09

Martijn Pieters


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'}
like image 42
intuited Avatar answered Sep 20 '22 23:09

intuited