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

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

Python, 5 lines
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

2 comments

Gabriel Genellina 12 years, 1 month ago  # | flag

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.

Thiago Holanda 10 years, 4 months ago  # | flag

The Adam's method doesn't work 'cause the dictionary just have the iteritems's method if the dictionary has just one level.

Example:

One Level:

a = {"name":"my name", "lastname": "my lastname", "age":"25"}

Two or more levels:

a = {"name":"my name", "lastname": "my lastname", "age":"25", "emails":[ {"home":"myname@myserver.com"}, {"work":"myname@mycompany.com"}, {"college":"myname@mycollege.com"} ] }

Created by Adam M Prost on Wed, 28 Oct 2009 (MIT)
Python recipes (4591)
Adam M Prost's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks