views:

142

answers:

5

Hi folks,

is there a similar library to simplejson, which would enable quick serialization of data to and from XML.

e.g. json.loads('{vol:'III', title:'Magical Unicorn'}')

e.g. json.dumps([1,2,3,4,5])

Any ideas?

+1  A: 

What about lxml?

Enchantner
+2  A: 

I don't know of one. Unless xmlrpc counts... In case you are thinking about rolling your own: Doing anything with ElementTree is a pleasure, compared with most other XML libraries.

But, since you'd probably end up with a representation that would be non-standarized, you would need to control both sides, right? Then why not just pick json, pickle or something that is already there?

In case you want to use the xmlrpclib module:

xmlrpclib.dumps(data)

Forest mentions limitations in xmlrpclib, which is a good point. Some that I've seen myself: Integers can't be more than 2^31-1 or the library will complain. "None" values typically aren't OK, but you can get around that. There are probably other limitations as well.

Apart from that, the xmlrpc-protocol is pretty verbose. if you need to worry about how much data is sent, it's not the best one. But no XML version will be very efficient.

Mattias Nilsson
+2  A: 

You're not going to find anything for xml as consistent as json, because xml doesn't know about data types. It depends on you to follow conventions or enforce adherence to an xml schema file.

That being said, if you're willing to accept the XML-RPC data structure mapping and a few limitations, check out the xmlrpclib package that lives in the Python standard library:

http://docs.python.org/library/xmlrpclib.html#convenience-functions

>>> import xmlrpclib
>>> s = xmlrpclib.dumps( ({'vol':'III', 'title':'Magical Unicorn'},))
>>> print s
<params>
<param>
<value><struct>
<member>
<name>vol</name>
<value><string>III</string></value>
</member>
<member>
<name>title</name>
<value><string>Magical Unicorn</string></value>
</member>
</struct></value>
</param>
</params>

>>> xmlrpclib.loads(s)[0]
({'vol': 'III', 'title': 'Magical Unicorn'},)
>>> 
Forest
In particular, that xmlrpc format has some limitations compared to json... only strings for dict keys. No none, booleans. (correct me if I'm wrong!)
Gregg Lind
Correction: you're wrong. :) Dict keys must be strings in json, too. Boolean values are supported by xmlrpclib, as is None if you pass the `allow_none=True` argument to dumps.
Forest
+2  A: 

It's not as straight forward with xml, as it is with json because, there is no "type mapping" between the datatypes of xml and python. Heck XML data can be anything, as mapped within the corresponding XSL.

As for the API is concerned, which you are mostly bothered about, I recommend Element Tree

For a good tutorial on Parsing XML using Element Tree, I refer you to Mark Pilgrim's Dive into Python3

Lakshman Prasad
+2  A: 

You can look how they have done it in Django: xml_serializer.py and tailor this to your needs.

Etienne