Created
September 29, 2016 20:07
-
-
Save devisnotnull/ab2c806bc26734945abe28d724c62b5c to your computer and use it in GitHub Desktop.
Python, XML-to-DICT. Really simple yet effective
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def etree_to_dict(t): | |
""" | |
A simple yet really powerful function for converting XML into a dict, | |
Faster than xmltodict | |
http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html | |
:param t: | |
:return: | |
""" | |
d = { | |
t.tag: {} if t.attrib else None | |
} | |
children = list(t) | |
if children: | |
dd = defaultdict(list) | |
for dc in map(etree_to_dict, children): | |
for k, v in dc.items(): | |
dd[k].append(v) | |
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.items()}} | |
if t.attrib: | |
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items()) | |
if t.text: | |
text = t.text.strip() | |
if children or t.attrib: | |
if text: | |
d[t.tag]['#text'] = text | |
else: | |
d[t.tag] = text | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment