Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract xml attribute using Python ElementTree

People also ask

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.


This will find the first instance of an element named bar and return the value of the attribute key.

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

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

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

Getting child tag's attribute value in a XML using ElementTree

Parse the XML file and get the root tag and then using [0] will give us first child tag. Similarly [1], [2] gives us subsequent child tags. After getting child tag use .attrib[attribute_name] to get value of that attribute.

>>> import xml.etree.ElementTree as ET
>>> xmlstr = '<foo><bar key="value">text</bar></foo>'
>>> root = ET.fromstring(xmlstr)
>>> root.tag
'foo'
>>> root[0].tag
'bar'
>>> root[0].attrib['key']
'value'

If the xml content is in file. You should do below task to get the root.

>>> tree = ET.parse('file.xml')
>>> root = tree.getroot()

Your expression:

./bar[@key]

It means: bar children having key attribute

If you want to select the attribute, use this relative expression:

bar/@key

It means: the key attribute of bar children

Of course, you need to consider to use a fully compliant XPath engine like lxml.