forked from spl0k/supysonic
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdict2xml.py
82 lines (67 loc) · 1.8 KB
/
dict2xml.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
Simple xml serializer.
@author Reimund Trost 2013
Example:
mydict = {
'name': 'The Andersson\'s',
'size': 4,
'children': {
'total-age': 62,
'child': [
{ 'name': 'Tom', 'sex': 'male', },
{
'name': 'Betty',
'sex': 'female',
'grandchildren': {
'grandchild': [
{ 'name': 'herbert', 'sex': 'male', },
{ 'name': 'lisa', 'sex': 'female', }
]
},
}
]
},
}
print(dict2xml(mydict, 'family'))
Output:
<family name="The Andersson's" size="4">
<children total-age="62">
<child name="Tom" sex="male"/>
<child name="Betty" sex="female">
<grandchildren>
<grandchild name="herbert" sex="male"/>
<grandchild name="lisa" sex="female"/>
</grandchildren>
</child>
</children>
</family>
"""
from xml.dom.minidom import Text
def dict2xml(d, root_node=None):
wrap = False if None == root_node or isinstance(d, list) else True
root = 'objects' if None == root_node else root_node
root_singular = root[:-1] if 's' == root[-1] and None == root_node else root
xml = ''
children = []
if isinstance(d, dict):
for key, value in dict.items(d):
if isinstance(value, dict):
children.append(dict2xml(value, key))
elif isinstance(value, list):
children.append(dict2xml(value, key))
else:
t = Text()
t.data = unicode(value)
xml = xml + ' ' + key + '="' + t.toxml() + '"'
else:
for value in d:
children.append(dict2xml(value, root_singular))
end_tag = '>' if 0 < len(children) else '/>'
if wrap or isinstance(d, dict):
xml = '<' + root + xml + end_tag
if 0 < len(children):
for child in children:
xml = xml + child
if wrap or isinstance(d, dict):
xml = xml + '</' + root + '>'
return xml