From f88a16f645d5359d494b78c2210c4edbffb56c62 Mon Sep 17 00:00:00 2001 From: David Sommerseth Date: Fri, 6 Mar 2009 15:21:46 +0100 Subject: Implemented XSLT processing to the XMLOut class --- rteval/xmlout.py | 53 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 8 deletions(-) (limited to 'rteval/xmlout.py') diff --git a/rteval/xmlout.py b/rteval/xmlout.py index a2ec87a..1b7d04e 100644 --- a/rteval/xmlout.py +++ b/rteval/xmlout.py @@ -3,6 +3,8 @@ import os import sys import libxml2 +import libxslt +import codecs class XMLOut(object): '''Class to create XML output''' @@ -52,6 +54,31 @@ class XMLOut(object): # If no XSLT template is give, write raw XML self.xmldoc.saveFormatFileEnc(filename, self.encoding, 1) return + else: + # Load XSLT file and prepare the XSLT parser + xsltdoc = libxml2.parseFile(xslt) + parser = libxslt.parseStylesheetDoc(xsltdoc) + + # imitate libxml2's filename interpretation + if filename != "-": + dstfile = codecs.open(filename, "w", encoding=self.encoding) + else: + dstfile = sys.stdout + # + # Parse XML+XSLT and write the result to file + # + resdoc = parser.applyStylesheet(self.xmldoc, None) + # Decode the result string according to the charset declared in the XSLT file + xsltres = parser.saveResultToString(resdoc).decode(parser.encoding()) + # Write the file with the requested output encoding + dstfile.write(xsltres.encode(self.encoding)) + + if dstfile != sys.stdout: + dstfile.close() + + # Clean up + resdoc.freeDoc() + xsltdoc.freeDoc() def __del__(self): if self.level > 0: @@ -79,16 +106,26 @@ class XMLOut(object): if __name__ == '__main__': - x = XMLOut('test_xml', {'version':"1.0"}) - x.openblock('test', {'testattr': "yes", 'works': "hopefully"}) - x.taggedvalue('foo', 'bar') - x.taggedvalue('baz', 'frooble', {'attrvalue':"1.0"}) - x.openblock('subtag', {'level': 1}) - x.openblock('subtag', {'level': 2}) - x.taggedvalue('value','another value') + x = XMLOut('rteval', {'version':"1.0"}, 'UTF-8') + x.openblock('run_info', {'days': 0, 'hours': 0, 'minutes': 32, 'seconds': 18}) + x.taggedvalue('time', '11:22:33') + x.taggedvalue('date', '2000-11-22') + x.closeblock() + x.openblock('uname') + x.taggedvalue('node', u'testing - \xe6\xf8') + x.taggedvalue('kernel', 'my_test_kernel', {'is_RT': 0}) + x.taggedvalue('arch', 'mips') x.closeblock() + x.openblock('hardware') + x.taggedvalue('cpu_cores', 2) + x.taggedvalue('memory_size', 1024*1024*2) x.closeblock() + x.openblock('loads', {'load_average': 3.29}) + x.taggedvalue('command_line','./load/loader --extreme --ultimate --threads 4096', {'name': 'heavyloader'}) + x.taggedvalue('command_line','dd if=/dev/zero of=/dev/null', {'name': 'lightloader'}) x.closeblock() - x.taggedvalue('node2',u'yet another value \xe6\xf8', {'shortvalue': "yav"}) x.close() + print "------------- XML OUTPUT ----------------------------" x.Write("-") + print "------------- XSLT PARSED OUTPUT --------------------" + x.Write("-", "rteval_text.xsl") -- cgit