Skip to content
Advertisement

Converting xml to dictionary using ElementTree

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

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement