xml_tree.html
001| '''XML Tree.
001|
001| commands:
001| main - Main function (normal use)
001| test - Test function (development)
001|
001| usage:
001| module.dispatch({command}, args={arguments}) -- calling module from code
001|
001| $PYTHON module_name {command} {arguments} -- executing module externally
001|
001| Developer@Sonnack.com
001| January 2019
001| '''
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from logger import logger, info
008| from dates import CST
009| from xml_sax import XmlHandlerMain, parse_xml_file
010|
011| BasePath = r'C:\CJS\prj\Python\ws\@sandbox'
012| DataPath = path.join(BasePath, 'dat')
013| Log = logger('XMLTREE')
014|
015| TestFiles = [
016| path.join(DataPath,'template-data.xml'),
017| ]
018|
019| ReplaceExtension = lambda fn:('%s.%s' % (path.splitext(fn)[0],'tree'))
020| FilenameOnly = lambda fn:(path.splitext(path.basename(fn))[0])
021|
022|
023|
024| def print_tree_node (node, fp):
025| s0 = '%s+---%s[%d]%s'
026| s1 = '%s| > @%s[%d]%s'
027| indent = ('| ' * node.level) if 0 < node.level else ''
028| text = (' "%s"' % node.sample) if node.sample else ''
029| t = (indent, node.name, node.count, text)
030| print(s0%t, file=fp)
031| for a in sorted(node.attribs):
032| attr = node.attribs[a]
033| text = (' "%s"' % attr[1]) if attr[1] else ''
034| t = (indent, a, attr[0], text)
035| print(s1%t, file=fp)
036|
037|
038|
039| class XmlTreeNode (object):
040| def __init__ (self, name, parent=None):
041| self.name = name
042| self.attribs = {}
043| self.children = {}
044| self.parent = parent
045| self.level = 0
046| self.count = 0
047| self.sample = ''
048|
049| def child (self, name, attrs):
050| if name not in self.children:
051| self.children[name] = XmlTreeNode(name, self)
052| node = self.children[name]
053| node.count += 1
054| for a in list(attrs.keys()):
055| if a not in node.attribs:
056| node.attribs[a] = [0, '']
057| node.attribs[a][0] += 1
058| node.attribs[a][1] = attrs[a]
059| return node
060|
061| def travel (self, cb_funct=None):
062| if cb_funct:
063| cb_funct(self)
064| for elem in sorted(self.children):
065| self.children[elem].travel(cb_funct)
066|
067| def __str__ (self):
068| s = '%s[%d]: (%d)'
069| t = (self.name, self.level, self.count)
070| return s%t
071|
072|
073| class XmlHandlerTree (XmlHandlerMain):
074| '''Generate a tree from an XML file.'''
075|
076| def __init__ (self, xmlfilename):
077| XmlHandlerMain.__init__(self, FilenameOnly(xmlfilename), log=Log)
078| self.root = XmlTreeNode('root')
079| self.curr = self.root
080| self.pathlist = {}
081| self.fname = xmlfilename
082| self.bname = path.basename(xmlfilename)
083| self.dname = path.dirname(xmlfilename)
084| self.fsize = path.getsize(xmlfilename)
085| self.dcr = datetime.fromtimestamp(path.getctime(xmlfilename), CST())
086| self.dlm = datetime.fromtimestamp(path.getmtime(xmlfilename), CST())
087| parse_xml_file(self.fname, self)
088|
089| def save (self, filename=None, cb_funct=print_tree_node):
090| node = list(self.root.children.values())[0]
091| oname = filename if filename else ReplaceExtension(self.fname)
092| fp = open(oname, mode='w', encoding='utf-8')
093| try:
094| fmt = '%b %d, %Y %I:%M:%S %p %Z'
095| print('[root]', file=fp)
096| print('> @timestamp "%s"' % datetime.now(CST()).strftime(fmt), file=fp)
097| print('> @filename "%s"' % self.bname, file=fp)
098| print('> @filepath "%s"' % self.dname, file=fp)
099| print('> @filesize "%d"' % self.fsize, file=fp)
100| print('> @created "%s"' % self.dcr.strftime(fmt), file=fp)
101| print('> @updated "%s"' % self.dlm.strftime(fmt), file=fp)
102| node.travel(lambda n:cb_funct(n,fp))
103| print(file=fp)
104| for p in sorted(self.pathlist):
105| print('[%5d] %s' % (self.pathlist[p], p), file=fp)
106| print(file=fp)
107| Log.info('wrote: %s' % oname)
108| except Exception as e:
109| Log.error(e)
110| raise
111| finally:
112| fp.close()
113|
114| def __str__ (self):
115| s = 'XTree: %s (%d bytes) [%s]'
116| t = (self.bname, self.fsize, self.dlm.strftime('%m-%d-%Y %H:%M:%S %Z'))
117| return s%t
118|
119|
120| def startElement (self, name, attrs):
121| XmlHandlerMain.startElement(self, name, attrs)
122| if self.log: self.log.debug('node: %s' % self.currpath)
123| node = self.curr.child(name, attrs)
124| node.level = self.depth
125| self.curr = node
126| if self.currpath not in self.pathlist:
127| self.pathlist[self.currpath] = 0
128| self.pathlist[self.currpath] += 1
129|
130| def endElement (self, name):
131| if 0 < len(self.buff):
132| self.curr.sample = self.buff.strip()[0:64]
133| self.curr = self.curr.parent
134| XmlHandlerMain.endElement(self, name)
135|
136|
137|
138| def do_tree (fname):
139| Log.info('tree: %s' % fname)
140| tree = XmlHandlerTree(fname)
141| tree.save(ReplaceExtension(fname))
142| Log.info(tree)
143| return 'Done.'
144|
145|
146| def do_test (*args):
147| Log.info('test:: %d' % len(args))
148| fname = args[0] if 0 < len(args) else TestFiles[0]
149| do_tree(fname)
150| return 'Done'
151|
152| def do_many (*args):
153| Log.info('many:: %d' % len(args))
154| for fn in args:
155| do_tree(fn)
156| return 'Done'
157|
158| def do_main (*args):
159| Log.info('file:: %d' % len(args))
160| fname = args[0]
161| do_tree(fname)
162| return 'Done'
163|
164| def dispatch (cmd, *args):
165| Log.info('command: %s' % cmd)
166| Log.info('arguments: %d' % len(args))
167| if cmd == '-f': return do_main(*args)
168| if cmd == '-F': return do_many(*args)
169| if cmd == 'test': return do_test(*args)
170| return 'Nothing to do!'
171|
172| if __name__ == '__main__':
173| print('autorun: %s' % argv[0])
174| Log.start(path.join(BasePath,'xmltree.log'))
175| Log.level(info())
176| cmd = argv[1] if 1 < len(argv) else 'test'
177| etc = argv[2:] if 2 < len(argv) else []
178| try:
179| obj = dispatch(cmd, *etc)
180| print(obj)
181| Log.info(obj)
182| except:
183| etype, evalue, tb = exc_info()
184| ts = extract_tb(tb)
185| Log.error('%s: %s' % (etype.__name__,str(evalue)))
186| for t in ts[-3:]:
187| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
188| Log.error(' %s' % t[3])
189| raise
190| finally:
191| Log.end()
192|
193| '''eof'''
194|