xml_sax.html
001| '''XML SAX Framework.
001|
001| classes:
001| Property (name, value, dtype=None)
001| XmlHandlerBase (saxhandler.ContentHandler)
001| XmlHandlerTest (XmlHandlerBase)
001| XmlHandlerMain (XmlHandlerBase)
001| XmlHandlerText (XmlHandlerMain)
001| XmlHandlerList (XmlHandlerMain)
001| XmlHandlerConfigBase (XmlHandlerMain)
001|
001| functions:
001| parse_xml_file (filename, config_handler)
001|
001| Developer@Sonnack.com
001| November 2016
001| '''
002|
003| from sys import stdout
004| from xml.sax import parse
005| from xml.sax.handler import ContentHandler
006| from xml.sax.xmlreader import Locator
007| from xml.sax.saxutils import unescape
008|
009|
010|
011|
012|
013| class Property (object):
014| '''Property class. Features data typed name-value pairs.'''
015| def __init__ (self, name, value, dtype=None):
016| self.name = name
017| self.value = value
018| self.dtype = dtype
019|
020| def __repr__ (self):
021| s = '{Property:{name:"%s", value:"%s", type:"%s"}}'
022| t = (self.name, str(self.value), self.dtype)
023| return s % t
024|
025| def __str__ (self):
026| v = self.value if self.value else ''
027| t = (':%s' % self.dtype) if self.dtype else ''
028| return '%s%s = %s' % (self.name, t, v)
029|
030| def __call__ (self):
031| return self.value
032|
033|
034|
035| class XmlHandlerBase (ContentHandler):
036| '''A basic XML parser framework using SAX. Strictly a base class.'''
037|
038| def __init__ (self, name, fout=None, log=None):
039| self.setDocumentLocator(Locator())
040| self.name = name
041| self.out = fout
042| self.depth = 0
043| self.state = 0
044| self.buff = ''
045| self.buff_enable = False
046| self.log = log
047|
048| def info (self, txt=''):
049| if self.log: self.log.info(txt)
050| def debug (self, txt=''):
051| if self.log: self.log.debug(txt)
052| def trace (self, txt=''):
053| if self.log: self.log.trace(txt)
054| def warn (self, txt=''):
055| if self.log: self.log.warn(txt)
056| def error (self, txt=''):
057| if self.log: self.log.error(txt)
058|
059| def __str__ (self):
060| return self.name
061|
062| def __repr__ (self):
063| s = '{XMLHandler:{name:"%s", state:%d, depth:%d, id:%d}}'
064| t = (self.name, self.state, self.depth, id(self))
065| return s % t
066|
067| def get_attribute (self, attrs, name):
068| return attrs[name] if name in attrs else ''
069|
070|
071| def startDocument (self):
072| self.debug('document: START <%s>' % self.name)
073| self.depth = 0
074| self.state = 0
075| self.buff = ''
076| self.buff_enable = False
077|
078| def endDocument (self):
079| self.debug('document: END')
080| if self.depth:
081| raise SyntaxError('Element Nesting Error!')
082|
083|
084| def characters (self, content):
085| if self.buff_enable:
086| self.buff += content
087|
088| def startElement (self, name, attrs):
089| self.trace('element: <%s> %s' % (name, list(attrs.keys())))
090| self.depth += 1
091| self.buff = ''
092| self.buff_enable = True
093|
094| def endElement (self, name):
095| self.trace('element: "%s" End' % name)
096| self.depth -= 1
097| if self.depth < 0:
098| raise SyntaxError('Element Nesting Error!')
099| self.buff = ''
100| self.buff_enable = False
101|
102|
103|
104| class XmlHandlerTest (XmlHandlerBase):
105| '''Implements the Prefix Mapping and NameSpace handler methods. A base class for testing.'''
106|
107|
108| def startPrefixMapping (self, prefix, uri):
109| self.warn('prefix: "%s":"%s"' % (prefix,uri))
110|
111| def endPrefixMapping (self, prefix):
112| self.warn('prefix: "%s" End' % prefix)
113|
114|
115| def startElementNS (self, name, qname, attrs):
116| self.warn('element: "%s" ("%s")' % (name,qname))
117| self.depth += 1
118| self.buff = ''
119| self.buff_enable = True
120|
121| def endElementNS (self, name, qname):
122| self.warn('element: "%s" ("%s") End' % (name,qname))
123| self.depth -= 1
124| if self.depth < 0:
125| raise SyntaxError('Element Nesting Error!')
126| self.buff = ''
127| self.buff_enable = False
128|
129|
130|
131| class XmlHandlerMain (XmlHandlerBase):
132| '''A generic XML parser base class. Does basic element text management. (Shows how to get started.)'''
133|
134| def __init__ (self, name, fout=stdout, log=None):
135| super().__init__(name, fout=fout, log=log)
136| self.text = ''
137| self.currpath = ''
138|
139|
140| def startElement (self, name, attrs):
141| super().startElement(name, attrs)
142| self.text = ''
143| self.currpath = '%s/%s' % (self.currpath, name)
144|
145| def endElement (self, name):
146| if self.buff:
147| self.text = unescape(self.buff)
148| else:
149| self.text = ''
150| self.currpath = self.currpath[0:-(len(name)+1)]
151| super().endElement(name)
152|
153|
154|
155| class XmlHandlerText (XmlHandlerMain):
156| '''A simple XML file element text extraction app. (Shows how to extend the Main class.)'''
157|
158| def __init__ (self, name, fout=stdout, log=None):
159| super().__init__(name, fout=fout, log=log)
160| self.text_content = []
161|
162|
163| def endElement (self, name):
164| super().endElement(name)
165| if len(self.text):
166| if self.out:
167| print('%s(%s)' % (name, self.text), file=self.out)
168| self.text_content.append(self.text)
169|
170|
171|
172| class XmlHandlerList (XmlHandlerMain):
173| '''A simple XML file list app. (A more practical demo of Main.)'''
174|
175| def __init__ (self, name, fout, log=None):
176| super().__init__(name, fout=fout, log=log)
177| self.indent = ''
178|
179|
180| def startElement (self, name, attrs):
181| if self.out:
182| self.indent = ('| ' * self.depth) if 0 < self.depth else ''
183| print('%s%s' % (self.indent, name), file=self.out)
184| for a in sorted(attrs.keys()):
185| print('%s @ %s="%s"' % (self.indent, a, attrs[a]), file=self.out)
186| super().startElement(name, attrs)
187|
188| def endElement (self, name):
189| super().endElement(name)
190| if len(self.text):
191| if self.out:
192| print('%s = "%s"' % (self.indent, self.text), file=self.out)
193|
194|
195|
196| class XmlHandlerConfigBase (XmlHandlerMain):
197| '''An XML Configuration file framework base class.'''
198| def __init__ (self, name, fout=stdout, log=None):
199| super().__init__(name, fout=fout, log=log)
200| self.props_list = []
201| self.config_list = []
202| self.curr_config = None
203|
204| def __len__ (self):
205| return len(self.config_list)
206|
207| def __iter__(self):
208| return iter(self.config_list)
209|
210| def __getitem__ (self, index):
211| self.curr_config = self.config_list[index]
212| return self.curr_config
213|
214| def __contains__ (self, index):
215| if index < 0: return False
216| if index < len(self): return True
217| return False
218|
219| def __setitem__(self, name, value):
220| raise NotImplementedError('Not allowed to modify the Configurations list!')
221|
222| def __delitem__ (self, ix):
223| raise NotImplementedError('Not allowed to modify the Configurations list!')
224|
225|
226| def startElement (self, name, attrs):
227| self.localStart(name, attrs)
228| super().startElement(name, attrs)
229|
230| def endElement (self, name):
231| super().endElement(name)
232| self.localEnd(name)
233|
234| def new_config_object (self, name):
235| '''Client classes MUST override this method!'''
236| return None
237|
238| def find_configuration (self, name):
239| '''Find a Config by name. (Sets current pointer.)'''
240| for cn in self:
241| if cn.name == name:
242| self.curr_config = cn
243| return cn
244| return None
245|
246| def print_configuration (self):
247| '''Client classes really SHOULD override this method!'''
248| if self.out:
249| print('Configuration: "%s"' % self.curr_config, file=self.out)
250|
251| def print_configurations (self):
252| if self.out:
253| print('::Configurations::', file=self.out)
254| print(file=self.out)
255| for prop in self.props_list:
256| print('. prop "%s"' % prop, file=self.out)
257| print(file=self.out)
258| for config in self.config_list:
259| self.curr_config = config
260| self.print_configuration()
261| print('::::', file=self.out)
262| self.curr_config = None
263|
264| def localStart (self, name, attrs):
265| '''Handles Configuration and PropertyList elements plus Property elements. (states: 100<0, 200<0, 201<200)'''
266|
267| if self.state == 0:
268| if name == 'Configuration':
269| self.state = 100
270| attr_name = self.get_attribute(attrs, 'name')
271| self.curr_config = self.new_config_object(attr_name)
272| self.debug('Configuration: "%s"' % attr_name)
273| return
274| if name == 'PropertyList':
275| self.trace('PropertyList:')
276| self.state = 200
277| return
278| return
279|
280| if self.state == 200:
281|
282| if name == 'Property':
283| self.state = 201
284| attr_name = self.get_attribute(attrs,'name')
285| attr_value = self.get_attribute(attrs,'value')
286| attr_type = self.get_attribute(attrs,'type')
287| prop = Property(attr_name, attr_value, attr_type)
288| self.props_list.append(prop)
289| return
290| return
291|
292| def localEnd (self, name):
293| '''Handles Configuration and PropertyList elements plus Property elements. (states: 0<100, 0<200, 200<201)'''
294|
295| if self.state == 100:
296| if name == 'Configuration':
297| self.state = 0
298| self.trace('Exit Configuration.')
299| self.config_list.append(self.curr_config)
300| self.curr_config = None
301|
302| return
303|
304| if self.state == 200:
305| if name == 'PropertyList':
306| self.state = 0
307| return
308|
309| if self.state == 201:
310| if name == 'Property':
311| self.state = 200
312| return
313| return
314|
315|
316|
317|
318| def parse_xml_file (filename, config_handler):
319| '''Given an XML filename and a config handler (extending XmlHandlerBase), parse the XML.'''
320| fp = open(filename, mode='rb')
321| try:
322|
323| config_handler.feature_namespaces = True
324| config_handler.feature_namespace_prefixes = True
325|
326|
327| parse(fp, config_handler)
328| except:
329| raise
330| finally:
331| fp.close()
332|
333|
334|
335|
336| '''eof'''
337|