ActiveState Code

Recipe 576939: Convert Dictionary to XML


A simple four line function for converting a dictionary into a simple xml string.

Python
1
2
3
4
5
def dict2xml(dict, xml = ''):
    for key,value in dict.iteritems():
        exec 'content = '+ {'str': 'value', 'dict': 'dict2xml(value)'}[type(value).__name__]
        xml += '<%s>%s</%s>' % (key, str(content), key)
    return xml

Comments

  1. 1. At 1:29 p.m. on 28 oct 2009, Gabriel Genellina said:

    It doesn't work for me, even with simple cases:

    >>> dict2xml({'hello': 1})
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in dict2xml
    KeyError: 'int'
    

    Using exec has really many problems (security, speed, ...) and it's not required here at all.

Sign in to comment