I’m looking for an XML to dictionary parser using ElementTree, I already found some but they are excluding the attributes, and in my case I have a lot of attributes.
Advertisement
Answer
JavaScript
x
6
1
def etree_to_dict(t):
2
d = {t.tag : map(etree_to_dict, t.iterchildren())}
3
d.update(('@' + k, v) for k, v in t.attrib.iteritems())
4
d['text'] = t.text
5
return d
6
Call as
JavaScript
1
3
1
tree = etree.parse("some_file.xml")
2
etree_to_dict(tree.getroot())
3
This works as long as you don’t actually have an attribute text
; if you do, then change the third line in the function body to use a different key. Also, you can’t handle mixed content with this.
(Tested on LXML.)