-
Notifications
You must be signed in to change notification settings - Fork 0
/
etXML.py
208 lines (181 loc) · 7.23 KB
/
etXML.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# -*- coding: windows-1251 -*-
# (c) Chernyavsky Alexey, 30.10.2008
import elementtree.ElementTree as ET
from sets import Set
from pprint import pprint
class etXMLException(Exception):
pass
class etXML:
"Base class of processing XML. Uses Element Tree"
tree = None
def __init__(self, filename=None, xmlstring=''):
self.filename = filename
self.xmlstring = xmlstring
self.getTree()
def getTree(self):
"ðàñïàðñèòü äåðåâî"
#parser = ET.XMLParser(encoding="windows-1251")
#self.tree = ET.parse(self.filename, parser=parser)
if self.xmlstring:
self.tree = ET.ElementTree(ET.XML(self.xmlstring))
elif self.filename:
self.tree = ET.parse(self.filename)
else:
self.tree = ET.ElementTree(ET.XML('<root></root>'))
def getElementsByTagName(self, TagName):
"ñòðîèò ñïèñîê âñåõ óçëîâ ïî èìåíè èõ òýãà"
Elements = []
for element in self.tree.iter(TagName):
Elements.append(element)
return Elements
def getElementsByAttrValue(self, TagName, AttrName, AttrValue):
"ñòðîèò ñïèñîê âñåõ óçëîâ ïî èìåíè èõ òýãà è çíà÷åíèþ åãî àòòðèáóòà"
Elements = []
for element in self.tree.iter(TagName):
if element.get(AttrName) == AttrValue:
Elements.append(element)
return Elements
def getChildsByTagName(self, ParentElem, ChTagName):
"ñòðîèò ñïèñîê äî÷åðíèõ óçëîâ ïî èìåíè èõ òýãà"
Elements = []
for element in ParentElem.iter():
if element.tag == ChTagName:
Elements.append(element)
return Elements
def getChildsByAttrValue(self, ParentElem, ChTagName, ChAttrName, ChAttrValue):
"ñòðîèò ñïèñîê äî÷åðíèõ ýëåìåíòîâ ïî çíà÷åíèþ èõ àòòðèáóòà"
Elements = []
for element in ParentElem.iter():
if element.tag == ChTagName:
if element.get(ChAttrName) == ChAttrValue:
Elements.append(element)
return Elements
def getAttrDic(self, Node):
"ñòðîèò îáúåêò-ñëîâàðü âñåõ àòòðèáóòîâ ýëåìåíòà"
if Node is None: return None
list = {}
if Node.keys():
for name, value in Node.items():
list[name] = value.encode('cp1251')
return list
def getChildAttrList(self, ParentElem):
"ñòðîèò ñïèñîê ñëîâàðåé âñåõ àòòðèáóòîâ ïðÿìûõ äî÷åðíèõ ýëåìåíòîâ äàííîãî ýëåìåíòà-ðîäèòåëÿ"
if ParentElem is None: return None
ls =[]
if list(ParentElem):
for child in ParentElem:
ls.append(self.getAttrDic(child))
return ls
def getAttrValue(self, Element, AttrName, coding=None):
"âîçâðàùàåò çíà÷åíèå àòðèáóòà äàííîãî ýëåìåíòà"
#if Element.keys():
# for name, value in Element.items():
# if name == AttrName:
# result = value
# return result
val = Element.get(AttrName)
if val is None:
return None
elif not coding is None:
return val.encode(coding)
else:
return val
def getAttrValueListbyElList(self, ElementsList, AttrName, _lstmode='lst', coding=None):
"âîçâðàùàåò ñïèñîê èëè ñòðîêó (_lstmode= ['lst','str']) çíà÷åíèé àòðèáóòîâ AttrName ñïèñêà ýëåìåíòîâ ElementsList"
if _lstmode == 'lst':
result = []
else:
result = ''
result
for element in ElementsList:
if _lstmode == 'lst':
result.append(self.getAttrValue(element, AttrName))
else:
result += ', '+self.getAttrValue(element, AttrName)
if _lstmode == 'str':
result = result[2:]
return result
def getChildsWithSubstr(self, ParentElem, substr):
"ñïèñîê äî÷åðíèõ ýëåìåíòîâ, òàã êîòîðûõ ñîäåðæèò çàäàííóþ ïîäñòðîêó"
Elements = []
for element in ParentElem.iter():
if substr in element.tag:
Elements.append(element)
return Elements
def prntSubElementsInfo(self, Element):
print "====elements info of " + str(Element)
for element in Element.iter():
print "Element: '%s'"%(element.tag)
if element.keys():
print "\tAttributes:"
for name, value in element.items():
print "\t\tName: '%s', Value: '%s'"%(name, value)
print "====end info================="
def prntElementItems(self, Element):
print "====direct child elements of " + str(Element)
for item in Element:
print item
print "====end info================="
### ===Lists as Sets======================================================= ###
def IntersectList(self, List1, List2):
"ïåðåñå÷åíèå äâóõ ñïèñêîâ"
if not List1 or not List2: return None
Intersection= Set(List1) & Set(List2)
result=[]
for item in Intersection:
result.append(item)
result.sort()
return result
def DifferenceList(self, List1, List2):
"ðàçíîñòü äâóõ ñïèñêîâ List1-List2"
if not List2 : return List1
if not List1 : return None
Difference= Set(List1) - Set(List2)
if len(Difference)==0: return None
result=[]
for item in Difference:
result.append(item)
result.sort()
return result
def UnionList(self, List1, List2):
"îáúåäèíåíèå äâóõ ñïèñêîâ"
if not List1 and not List2: return None
Union = Set(List1) | Set(List2)
result=[]
for item in Union:
result.append(item)
result.sort()
return result
### ===saving Elements======================================================= ###
def SubElement(self, ParentEl, TagName, AttrsDic={}):
return ET.SubElement(ParentEl, TagName, AttrsDic)
def writeTree(self, filename=None, encoding="us-ascii"):
if not filename:
filename = self.filename
if not filename:
raise etXMLException('etXML.writeTree: filename argument is not supplied and has not been passed to constructor!')
return self.tree.write(filename, encoding)
### ========================================================================= ###
#def getElementsByPathAttrValue(self, Path, AttrName, AttrValue):
# "âîçâðàùàåò ñïèñîê ýëåìåíòîâ, èìåþùèõ àòòðèáóò AttrName ñî çíà÷åíèåì AttrValue"
# return self.tree.findall(Path + "[@" + AttrName + "='" + AttrValue + "']")
def findElemInListByAttr(self, ElementsList, AttrName, AttrValue):
"èùåò 1-é ýëåìåíò â ñïèñêå ElementsList ñî çíà÷åíèåì àòòðèáóòà AttrName ðàâíîì AttrValue"
found = False
for challenger in ElementsList:
if self.getAttrValue(challenger, AttrName) == AttrValue:
found = True
break
if not found:
return None
return challenger
def getroot(self):
return self.tree.getroot()
def findall(self, path):
return self.tree.findall(path)
def find(self, path):
return self.tree.find(path)
def dump(self, Element=None):
if Element is None:
Element = self.getroot()
ET.dump(Element)