A simple four line function for converting a dictionary into a simple xml string.
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
|
It doesn't work for me, even with simple cases:
Using exec has really many problems (security, speed, ...) and it's not required here at all.
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"} ] }