-
Notifications
You must be signed in to change notification settings - Fork 1
/
dict2xml.py
38 lines (30 loc) · 1.1 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
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:
xml = xml + ' ' + key + '="' + str(value) + '"'
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
if __name__ == "__main__":
d = {'key1': 'item'}
xml = dict2xml(d)
print(xml)