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:
&
ElementTree 1.3 (unfortunately not 1.2 which is the one included with Python) supports XPath like this:
import elementtree.ElementTree as xml
def getValues(tree, category):
parent = tree.find(".//parent[@name='%s']" % category)
return [child.get('value') for child in parent]
Then you can do
>>> tree = xml.parse('data.xml')
>>> getValues(tree, 'CategoryA')
['a1', 'a2', 'a3']
>>> getValues(tree, 'CategoryB')
['b1', 'b2', 'b3']
lxml.etree (which also provides the ElementTree interface) will also work in the same way.