Re: looking for conversion from dictionary

Fredrik Lundh <[email protected]>
Newsgroups gmane.comp.python.xml
Message-ID <[email protected]>
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]
...
 >>> ET.tostring(e)
'<dict><foo>Foo!</foo><bar>Bar!</bar></dict>'

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
'<params>\n<param>\n<value><struct>\n<member>\n<name>foo</name>\n<value><string>
Foo!</string></value>\n</member>\n<member>\n<name>bar</name>\n<value><string>Bar
!</string></value>\n</member>\n</struct></value>\n</param>\n</params>\n'

see the library reference for details.

hope this helps!

</F>

_______________________________________________
XML-SIG maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/xml-sig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.