Welcome, guest | Sign In | My Account | Store | Cart

Uses lxml.etree to convert a Python object consisting of nested dicts, tuples, lists, strings and string-convertable objects into a very basic no-attributes, untyped dialect of XML in which elements are named after dictionary keys, and "<i>" is the element for anonymous list and tuple items.

Does not support: encoding or decoding of strings, invalid floating point values, detection of circular references.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import lxml.etree as et

def data2xml(d, name='data'):
    r = et.Element(name)
    return et.tostring(buildxml(r, d))

def buildxml(r, d):
    if isinstance(d, dict):
        for k, v in d.iteritems():
            s = et.SubElement(r, k)
            buildxml(s, v)
    elif isinstance(d, tuple) or isinstance(d, list):
        for v in d:
            s = et.SubElement(r, 'i')
            buildxml(s, v)
    elif isinstance(d, basestring):
        r.text = d
    else:
        r.text = str(d)
    return r

print data2xml({'a':[1,2,('c',{'d':'e'})],'f':'g'})
# <data><a><i>1</i><i>2</i><i><i>c</i><i><d>e</d></i></i></a><f>g</f></data>

This may be useful to interface things, such as XSL transformations, that want your data as some kind (any kind) of XML.