public
Created

Convert python dictionary to xml

  • Download Gist
xmlutils.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
from xml.dom import minidom
from collections import Mapping
 
def dict2element(root,structure,doc):
"""
Gets a dictionary like structure and converts its
content into xml elements. After that appends
resulted elements to root element. If root element
is a string object creates a new elements with the
given string and use that element as root.
 
This function returns a xml element object.
 
"""
assert isinstance(structure,Mapping), 'Structure must be a mapping object such as dict'
# if root is a string make it a element
if isinstance(root,str):
root = doc.createElement(root)
 
for key,value in structure.iteritems():
el = doc.createElement(str(key))
if isinstance(value,Mapping):
dict2element(el,value,doc)
else:
el.appendChild(doc.createTextNode(str(value) if value is not None else ''))
root.appendChild(el)
return root
 
def dict2xml(structure,tostring=False):
"""
Gets a dict like object as a structure and returns a corresponding minidom
document object.
 
If str is needed instead of minidom, tostring parameter can be used
Restrictions:
Structure must only have one root.
Structure must consist of str or dict objects (other types will
converted into string)
 
Sample structure object would be
{'root':{'elementwithtextnode':'text content','innerelements':{'innerinnerelements':'inner element content'}}}
result for this structure would be
'<?xml version="1.0" ?>
<root>
<innerelements><innerinnerelements>inner element content</innerinnerelements></innerelements>
<elementwithtextnode>text content</elementwithtextnode>
</root>'
"""
# This is main function call. which will return a document
assert len(structure) == 1, 'Structure must have only one root element'
assert isinstance(structure,Mapping), 'Structure must be a mapping object such as dict'
 
root_element_name, value = next(structure.iteritems())
impl = minidom.getDOMImplementation()
doc = impl.createDocument(None,str(root_element_name),None)
dict2element(doc.documentElement,value,doc)
return doc.toxml() if tostring else doc

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.