[XML-SIG] looking for conversion from dictionary
fredrik at pythonware.com
Wed Jun 6 11:26:35 CEST 2007
David Bear wrote:
> I google for 'convert python dictionary xml' but got way too many hits.
> Anyone have any pointers for a quick way to have a python dictionary
> represented as xml? I want to have repr(pythondict) where
> <tagname>=keyname, and the contents of the tag is the value.
your problem is a bit underspecified (to say the least), but assuming
well-formed string keys and string values, here's one way to do it:
>>> d = dict(foo="Foo!", bar="Bar!")
>>> import xml.etree.ElementTree as ET
>>> e = ET.Element("dict")
>>> for k in d:
... ET.SubElement(e, k).text = d[k]
if you want to support than just straightforward string/string mappings,
you might want to look for XML serialization libraries instead.
Python's standard xmlrpclib module can be used for this purpose:
>>> import xmlrpclib
>>> xmlrpclib.dumps((d,)) # dumps wants the data wrapped in a tuple
see the library reference for details.
hope this helps!
More information about the XML-SIG