convert dictionary / list structures into xml structure
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 | from xml.dom.minidom import Document
import copy
class dict2xml(object):
doc = Document()
def __init__(self, structure):
if len(structure) == 1:
rootName = str(structure.keys()[0])
self.root = self.doc.createElement(rootName)
self.doc.appendChild(self.root)
self.build(self.root, structure[rootName])
def build(self, father, structure):
if type(structure) == dict:
for k in structure:
tag = self.doc.createElement(k)
father.appendChild(tag)
self.build(tag, structure[k])
elif type(structure) == list:
grandFather = father.parentNode
tagName = father.tagName
grandFather.removeChild(father)
for l in structure:
tag = self.doc.createElement(tagName)
self.build(tag, l)
grandFather.appendChild(tag)
else:
data = str(structure)
tag = self.doc.createTextNode(data)
father.appendChild(tag)
def display(self):
print self.doc.toprettyxml(indent=" ")
if __name__ == '__main__':
example = {'sibbling':{'couple':{'mother':'mom','father':'dad','children':[{'child':'foo'},
{'child':'bar'}]}}}
xml = dict2xml(example)
xml.display()
|
Tags: dictionary, xml
Hi!
2 little problems:
line: self.__build(tag, l) must be: self.build(tag, l)
end this line is missing: xml=dict2xml(example) (in antepenultimate position)
@Claveau thanks for the hints i changed the line(s)