Welcome, guest | Sign In | My Account | Store | Cart

convert dictionary / list structures into xml structure

Python, 44 lines
 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()

2 comments

Claveau Michel 12 years, 9 months ago  # | flag

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)

nuggetier (author) 12 years, 9 months ago  # | flag

@Claveau thanks for the hints i changed the line(s)

Created by nuggetier on Tue, 7 Jun 2011 (GPL3)
Python recipes (4591)
nuggetier's recipes (1)

Required Modules

Other Information and Tasks

  • Licensed under the GPL 3
  • Viewed 9146 times
  • Revision 4 (updated 12 years ago)