Converting xml to dictionary using ElementTree

dictionary, elementtree, python, xml

Solution

def etree_to_dict(t):
    d = {t.tag : map(etree_to_dict, t.iterchildren())}
    d.update(('@' + k, v) for k, v in t.attrib.iteritems())
    d['text'] = t.text
    return d

Call as

tree = etree.parse("some_file.xml")
etree_to_dict(tree.getroot())

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.)

Problem

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.

Original source

Related problems