简体   繁体   中英

XML library similar to simplejson/json? - Python

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?

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'},)
>>> 

你可以看看他们是如何在Django中完成它的: xml_serializer.py并根据你的需要定制它。

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.

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

那么lxml呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM