Convert Python Dictionary to XML
I was looking around for a function to do this but I couldn’t find one that did what I wanted. I found plenty of functions to convert XML to a python dictionary, but nothing to go the other way around. I wrote this quick little class that can accomplish this, along with convenience functions for easy usage (without using the oop approach).
Examples
Below I have two examples on how to use the class I have written. The first example uses the Object-Orient Approach, and the second example uses some helper functions to accomplish the same task.
Object-Oriented Approach
>>> import XMLDict
>>> obj = { "people" : { "person" : [ "dave", "john", "steve", "mike", "jack" ] } }
>>> xml_dict = XMLDict.XMLDict(obj)
>>> print xml_dict.get_xml()
<people><person>dave</person><person>john</person><person>steve</person><person>mike</person><person>jack</person></people>
>>> print xml_dict.get_pretty_xml()
<?xml version="1.0" ?>
<people>
<person>
dave
</person>
<person>
john
</person>
<person>
steve
</person>
<person>
mike
</person>
<person>
jack
</person>
</people>
>>>
Convenience Methods
>>> import XMLDict
>>> obj = { "people" : { "person" : [ "dave", "john", "steve", "mike", "jack" ] } }
>>> print XMLDict.convert_dict_to_xml(obj)
<people><person>dave</person><person>john</person><person>steve</person><person>mike</person><person>jack</person></people>
>>> print XMLDict.prettify(XMLDict.convert_dict_to_xml(obj))
<?xml version="1.0" ?>
<people>
<person>
dave
</person>
<person>
john
</person>
<person>
steve
</person>
<person>
mike
</person>
<person>
jack
</person>
</people>
>>>
Source
The code can be found on github at https://github.com/bahamas10/xmlserialize
Pingback: Dave Eddy » Blog Archive » Convert Python Dictionary to XML | All dropped packets go to heaven
Hi. The is_dict and is_list functions can be written as:
def _is_dict(self, a):
”"”Returns True if the item is a dictionary”"”
return type(a) == type({})
def _is_list(self, a):
”"”Returns True if the item is a list”"”
return type(a) == type([])
since the equality operator == evaluates to a Boolean.
@eric very true, that’s a nicer/more elegant way of writing that, I changed the script in the post to reflect it.
Thanks!
Great code. Very useful.. Thanks:) keep up the good work. you rock.
Pingback: My Kingdom for a light weight Python XML Library utilizing ElementTree | The Angry Geek