Skip to content

Instantly share code, notes, and snippets.

@pykong
Last active December 10, 2017 18:52
Show Gist options
  • Save pykong/6ff7e3c3acb652291292b4174adb2828 to your computer and use it in GitHub Desktop.
Save pykong/6ff7e3c3acb652291292b4174adb2828 to your computer and use it in GitHub Desktop.
Recursively transform even nested dicts to xml. (This is my own creation do not confuse with the dedicated library: https://pypi.python.org/pypi/dicttoxml) Plus: Tuple to xml converter.
from xml.etree.ElementTree import Element, tostring
def dict_to_xml(tag, d):
'''
Turn a simple dict of key/value pairs into XML
'''
elem = Element(tag)
for key, val in d.items():
if type(val) == dict:
child = dict_to_xml("tag", val)
else:
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
s = {'name': 'GOOG', 'shares': 100, 'price': 490.1, 'hello':{'a':'b'}}
e = dict_to_xml('stock', s)
print(tostring(e))
print(e)
def tup_to_xml(tup):
'''
Turn a nested tuplpe into XML
'''
elem = Element(tup[0])
for t in tup:
print(t)
if type(t) == tuple:
child = Element(t[0])
child.text = str(t[1])
else:
child = tup_to_xml(t)
elem.append(child)
return elem
test_tup = ("dict", ("key", "name"),
("string", "SublimeLinter Warning"),
("key", "scope"),
("string", "sublimelinter.mark.warning"),
("key", "settings"),
("dict",
(
("key", "foreground")
)))
print(tostring(tup_to_xml(test_tup)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment