1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/XSLOutput.py Mon Dec 20 00:30:39 2004 +0000
1.3 @@ -0,0 +1,102 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +XSL output classes and functions.
1.8 +"""
1.9 +
1.10 +# NOTE: Make this use other implementations, too.
1.11 +
1.12 +import libxslt
1.13 +import libxml2dom
1.14 +
1.15 +class OutputError(Exception):
1.16 + pass
1.17 +
1.18 +class Processor:
1.19 +
1.20 + """
1.21 + A handler which can prepare output for an XMLTools2 template.
1.22 + """
1.23 +
1.24 + def __init__(self, filenames, references=None):
1.25 +
1.26 + """
1.27 + Initialise the handler with the 'filenames' of stylesheets producing the
1.28 + final output, a 'references' dictionary indicating related stylesheets.
1.29 + """
1.30 +
1.31 + self.references = references or {}
1.32 +
1.33 + # Remember the stylesheet documents.
1.34 +
1.35 + self.stylesheets = []
1.36 + for filename in filenames:
1.37 + self.stylesheets.append(libxslt.parseStylesheetFile(filename))
1.38 +
1.39 + def __del__(self):
1.40 +
1.41 + """
1.42 + Tidy up the stylesheet documents.
1.43 + """
1.44 +
1.45 + for stylesheet in self.stylesheets:
1.46 + stylesheet.freeStylesheet()
1.47 +
1.48 + def send_output(self, stream, encoding, document):
1.49 +
1.50 + """
1.51 + Send output to the given 'stream' using the given output encoding for
1.52 + the given 'document'.
1.53 + """
1.54 +
1.55 + result = self._get_result(document)
1.56 +
1.57 + if result is not None:
1.58 + # Since result is a native node, use the serialize method.
1.59 + stream.write(result.serialize(encoding))
1.60 + result.freeDoc()
1.61 + else:
1.62 + raise OutputError, "Transformation failed."
1.63 +
1.64 + def get_result(self, document):
1.65 +
1.66 + """
1.67 + Return a transformed document produced from the object's stylesheets and
1.68 + the given 'document'.
1.69 + """
1.70 +
1.71 + result = self._get_result(document)
1.72 +
1.73 + if result is not None:
1.74 + return libxml2dom.Node(result)
1.75 + else:
1.76 + raise OutputError, "Transformation failed."
1.77 +
1.78 + def _get_result(self, document):
1.79 +
1.80 + """
1.81 + Return a transformation of the given 'document'.
1.82 + """
1.83 +
1.84 + if hasattr(document, "as_native_node"):
1.85 + document = document.as_native_node()
1.86 +
1.87 + # Transform the localised instance into the final output.
1.88 +
1.89 + parameters = {}
1.90 + for name, reference in self.references.items():
1.91 + parameters[name.encode("utf-8")] = ("document('%s')" % reference).encode("utf-8")
1.92 +
1.93 + last_result = document
1.94 + for stylesheet in self.stylesheets:
1.95 + result = stylesheet.applyStylesheet(last_result, parameters)
1.96 + if last_result is not None:
1.97 + if last_result != document:
1.98 + last_result.freeDoc()
1.99 + last_result = result
1.100 + else:
1.101 + raise OutputError, "Transformation failed."
1.102 +
1.103 + return result
1.104 +
1.105 +# vim: tabstop=4 expandtab shiftwidth=4