sanand0 / xmljson

xmlsjon converts XML into Python dictionary structures (trees, like in JSON) and vice-versa.
MIT License
121 stars 33 forks source link

gdata to json to xml #12

Closed pandemicsyn closed 7 years ago

pandemicsyn commented 7 years ago

Hi, In one of your stackoverflow answers referencing this library. You mention that:

It's possible to convert from XML to JSON and from JSON to XML using the same conventions

But how to best do that is a bit non-obvious to me. I'm dumping a gdata object to json using this library, but how do I convert back from json to an xml string. I assume I json.loads into an ordered dict ? Is there a method that will then convert that back into an xml string I can feed atom.core.parse() or the like ?

My python's a bit rusty so this might be kind of a dumb question. As an aside, you should setup Gratipay or Paetron, this is a pretty useful library!

sanand0 commented 7 years ago

@pandemicsyn -- you can use the lxml library to convert the XML element to a string. Here's a code sample:

>>> from xmljson import gdata
>>> element = gdata.etree({'p': {'id': 'main', 'text': 'Hello', 'b': 'bold'}})[0]
>>> from lxml import etree
>>> etree.tostring(element)
'<p text="Hello" b="bold" id="main"/>'

The function gdata.etree(valid_json_object) returns an XML element. The function etree.tostring(element) converts it to a string.

Glad you're finding it useful. Will look at Gratipay / Paetron!