开发者

XML library similar to simplejson/json? - Python

开发者 https://www.devze.com 2023-01-02 12:08 出处:网络
is there a similar library to simplejson, which would enable quick serialization of data to and from XML.

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 i开发者_C百科deas?


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


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


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


What about lxml?

0

精彩评论

暂无评论...
验证码 换一张
取 消