Skip to content

Instantly share code, notes, and snippets.

@willcalderbank
Created November 20, 2014 09:43
Show Gist options
  • Save willcalderbank/2067b669687b56e515c8 to your computer and use it in GitHub Desktop.
Save willcalderbank/2067b669687b56e515c8 to your computer and use it in GitHub Desktop.
Convert xml to dict
from collections import defaultdict
import functools
from lxml import etree
def etree_to_dict(t, ns=None):
"""
http://stackoverflow.com/questions/2148119/how-to-convert-an-xml-string-to-a-dictionary-in-python
"""
def strip_ns(tag):
if ns:
return tag.replace('{%s}' % ns, '')
return tag
d = {strip_ns(t.tag): {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(functools.partial(etree_to_dict, ns=ns), children):
for k, v in dc.iteritems():
dd[k].append(v)
d = {strip_ns(t.tag): {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
if t.attrib:
d[strip_ns(t.tag)].update(('@' + k, v) for k, v in t.attrib.iteritems())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[strip_ns(t.tag)]['#text'] = text
else:
d[strip_ns(t.tag)] = text
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment