-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxml2dic.py
45 lines (33 loc) · 859 Bytes
/
xml2dic.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
# -*- coding: utf-8 -*-
##Module that converts the Xml response to dictionary
from lxml import etree
def dictlist(node):
res = {}
res[node.tag] = []
xmltodict(node,res[node.tag])
reply = {}
reply[node.tag] =res[node.tag]
return reply
def xmltodict(node,res):
rep = {}
if len(node):
#n = 0
for n in list(node):
rep[node.tag] = []
value = xmltodict(n,rep[node.tag])
if len(n):
value = rep[node.tag]
res.append({n.tag:value})
else :
res.append(rep[node.tag][0])
else:
value = {}
value = node.text
res.append({node.tag:value})
return
def main(xml_string):
tree = etree.fromstring(xml_string)
res = dictlist(tree)
return res
if __name__ == '__main__' :
main()