-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict_to_xml.py
73 lines (57 loc) · 2.17 KB
/
dict_to_xml.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
#!/usr/bin/env python
from xml.dom.minidom import DOMImplementation
class Dict_To_XML:
def __init__(self):
self.doctype = None
self.name_sep = ' '
self.attr_sep = '='
def dict_to_xml(self,dic):
if not isinstance(dic,dict):
return None
dom_impl = DOMImplementation()
if self.doctype:
doctype = dom_impl.createDocumentType(self.doctype[0],self.doctype[1],self.doctype[2])
else:
doctype = None
if dic:
if len(dic) > 1:
dic = {'Root':dic}
root_name = list(dic.keys())[0]
doc = dom_impl.createDocument(None,root_name,doctype)
root = doc.lastChild
for ele in self.to_xml(doc,dic[root_name]):
root.appendChild(ele)
#@todo: toprettyxml will change textnode
return doc.toxml()
def to_xml(self,doc,seq,alone=True):
eles = []
if isinstance(seq,dict):
for key in seq:
attrs = key.split(self.name_sep)
ele = doc.createElement(attrs[0])
for attr in attrs[1:]:
attr = attr.split(self.attr_sep)
ele.setAttribute(attr[0],attr[1])
c_eles = self.to_xml(doc,seq[key])
for c_ele in c_eles:
ele.appendChild(c_ele)
eles.append(ele)
elif isinstance(seq,list):
for ele in seq:
c_eles = self.to_xml(doc,ele,False)
eles += c_eles
else:
seq = self.to_str(seq)
if alone:
ele = doc.createTextNode(seq)
else:
ele = doc.createComment(seq)
eles.append(ele)
return eles
def to_str(self,var):
if not isinstance(var,str):
var = repr(var)
return var
#import time
#dx = Dict_To_XML()
#print(dx.dict_to_xml({'background':['Generated by WallPaper @ '+time.strftime('%Y-%m-%d %H:%M:%S'),{'starttime':{'year':'2009','month':'08','day':'04','hour':'00','minute':'00','second':'00'}}]}))