-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdict2xml.py
53 lines (46 loc) · 1.53 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
from xml.etree.cElementTree import Element, SubElement
from xml.sax.saxutils import escape
def _dict2xml(src, parent_element=None):
_res = []
if isinstance(src, dict):
for name, value in src.iteritems():
if isinstance(value, dict):
if parent_element is None:
_ = Element(name)
else:
_ = SubElement(parent_element, name)
_dict2xml(value, _)
_res.append(_)
elif isinstance(value, list):
for item in value:
if parent_element is None:
_ = Element(name)
else:
_ = SubElement(parent_element, name)
_dict2xml(item, _)
_res.append(_)
else:
if name == '_text':
parent_element.text = escape(
str(value),
{
'"': '"',
"'": '''
}
)
else:
parent_element.attrib.update({name: str(value)})
elif isinstance(src, list):
for item in src:
for sub_item in dict2xml(item, parent_element):
_res.append(sub_item)
return _res
def dict2xml(src):
if not isinstance(src, dict):
return None
_ = _dict2xml(src)
if len(_) == 0:
_ = None
elif len(_) == 1:
_ = _[0]
return _