Created
October 21, 2016 09:27
-
-
Save rbarzic/809f3426dc65c82ae928cd5c325844a1 to your computer and use it in GitHub Desktop.
Python Xml to Dict & Dict to XML
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
#!/usr/bin/env python | |
from xml.etree import ElementTree as ET | |
import pprint as pp | |
import argparse | |
from collections import defaultdict | |
# From http://stackoverflow.com/questions/2148119/how-to-convert-an-xml-string-to-a-dictionary-in-python/10077069#10077069 | |
def etree_to_dict(t): | |
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.iteritems(): | |
dd[k].append(v) | |
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}} | |
if t.attrib: | |
d[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[t.tag]['#text'] = text | |
else: | |
d[t.tag] = text | |
return d | |
try: | |
basestring | |
except NameError: # python3 | |
basestring = str | |
def dict_to_etree(d): | |
def _to_etree(d, root): | |
if not d: | |
pass | |
elif isinstance(d, basestring): | |
root.text = d | |
elif isinstance(d, dict): | |
for k,v in d.items(): | |
assert isinstance(k, basestring) | |
if k.startswith('#'): | |
assert k == '#text' and isinstance(v, basestring) | |
root.text = v | |
elif k.startswith('@'): | |
assert isinstance(v, basestring) | |
root.set(k[1:], v) | |
elif isinstance(v, list): | |
for e in v: | |
_to_etree(e, ET.SubElement(root, k)) | |
else: | |
_to_etree(v, ET.SubElement(root, k)) | |
else: | |
raise TypeError('invalid type: ' + str(type(d))) | |
assert isinstance(d, dict) and len(d) == 1 | |
tag, body = next(iter(d.items())) | |
node = ET.Element(tag) | |
_to_etree(body, node) | |
return ET.tostring(node) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment