spock
10/9/2017 - 6:58 PM

Dictionary to XML converter.

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.

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