I need to get a list of attribute values from child elements in Python.
It\'s easiest to explain with an example.
Given some XML like this:
&
In Python 3.x, fetching a list of attributes is a simple task of using the member items()
Using the ElementTree
, below snippet shows a way to get the list of attributes.
NOTE that this example doesn't consider namespaces, which if present, will need to be accounted for.
import xml.etree.ElementTree as ET
flName = 'test.xml'
tree = ET.parse(flName)
root = tree.getroot()
for element in root.findall(''):
attrList = element.items()
print(len(attrList), " : [", attrList, "]" )
REFERENCE:
Element.items()
Returns the element attributes as a sequence of (name, value) pairs.
The attributes are returned in an arbitrary order.
Python manual