-
Notifications
You must be signed in to change notification settings - Fork 0
/
sampleXml.py
123 lines (106 loc) · 3.87 KB
/
sampleXml.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/python
# -*- coding=UTF-8 -*-
try:
from collections import OrderedDict as dict
except ImportError:
pass
class sampleXml:
def __init__(self,file):
self.file = file
self.xmlLst = self.readXml()
self.xmlDict = self.xml2Dict(self.xmlLst)
def readXml(self):
try:
fd = open(self.file)
xmlLst = fd.readlines()
fd.close()
return xmlLst
except Exception,e:
print e
return False
def xml2Dict(self,xmlLst):
xmlDict = {}
xmlDict["attribute"] = dict()
xmlDict["data"] = []
xmlDict["name"] = ""
if xmlLst[0].strip().startswith("<?xml"):
firLine = xmlLst[0].strip().split()
for item in firLine:
item = item.strip()
if item.startswith("<"):
xmlDict["name"] = item.split()[0].replace('<','').replace('>','')
elif '=' in item:
key,value = item.split('=')
xmlDict["attribute"][key]=value.replace('"','')
xmlDict["data"].append(self.xml2Dict(xmlLst[1:]))
return xmlDict
if xmlLst[0].startswith("<!--"):
while xmlLst and not xmlLst[0].strip().endswith("/-->"):
xmlLst.pop(0)
xmlLst.pop(0)
if not xmlLst:
return xmlDict
firLine = xmlLst[0].strip().split()
xmlDict["name"] = firLine[0].split()[0].replace('<','').replace('>','')
for item in firLine[1:]:
item = item.strip()
if item.endswith('>'):
item = item[:-1].strip()
if '=' in item:
key,value = item.split('=')
xmlDict["attribute"][key] = value.replace('"','')
if len(xmlLst) == 1:
return xmlDict
nodeName = ""
childNode = []
for line in xmlLst[1:-1]:
try:
line = line.strip()
if nodeName:
childNode.append(line)
if line == "</%s>" % nodeName:
xmlDict["data"].append(self.xml2Dict(childNode))
childNode = []
nodeName = ""
elif line.endswith("/>"):
xmlDict["data"].append(self.xml2Dict([line]))
elif line.startswith("<") and not line.startswith("<!--"):
lineLst = line.split()
nodeName = lineLst[0].split()[0].replace('<','').replace('>','')
childNode.append(line)
except Exception as e:
print e
return xmlDict
def dict2XmlLst(self,dictionary):
retStr = ""
attrStr = " ".join(["%s=\"%s\"" % (key,value) for key,value in dictionary["attribute"].items()])
if not dictionary["data"]:
retStr = "<%s %s />" % (dictionary["name"],attrStr)
return [retStr]
headStr = "<%s>" % (dictionary["name"])
endStr = "</%s>" % (dictionary["name"])
splitStr ="\t"
if attrStr:
headStr = "<%s %s>" % (dictionary["name"],attrStr)
if dictionary["name"] == "?xml":
headStr = "<%s %s ?>" % (dictionary["name"],attrStr)
endStr = ""
splitStr=""
retLst = []
retLst.append(headStr)
for secDict in dictionary["data"]:
try:
secLst = self.dict2XmlLst(secDict)
retLst.extend([splitStr+word for word in secLst])
except Exception as e:
print e
retLst.append(endStr)
return retLst
def write(self,fileName,xmlDict=""):
if not xmlDict:
xmlDict = self.xmlDict
fd = open(fileName,'w')
fd.write("\n".join(self.dict2XmlLst(xmlDict)))
fd.close()
def __del__(self):
pass