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:
&
My preferred python xml library is lxml , which wraps libxml2.
Xpath does seem the way to go here, so I'd write this as something like:
from lxml import etree
def getValues(xml, category):
return [x.attrib['value'] for x in
xml.findall('/parent[@name="%s"]/*' % category)]
xml = etree.parse(open('filename.xml'))
>>> print getValues(xml, 'CategoryA')
['a1', 'a2', 'a3']
>>> print getValues(xml, 'CategoryB')
['b1', 'b2', 'b3]