def _compile_xsl(XSLT_FILE, XSLT_COMPILED_FILE): """ compiling docbook stylesheet reference: http://155.210.85.193:8010/ccia/nodes/2005-03-18/compileXslt?xslt=/akara/akara.xslt """ from Ft.Xml.Xslt.Processor import Processor from Ft.Xml.Xslt import Stylesheet from Ft.Xml import InputSource from Ft.Lib import Uri # New docbook processor db_processor = Processor() # Docbook Stylesheet my_sheet_uri = Uri.OsPathToUri(XSLT_FILE, 1) sty_isrc = InputSource.DefaultFactory.fromUri(my_sheet_uri) # Append Stylesheet db_processor.appendStylesheet(sty_isrc) # Pickled stylesheet will be self.abs_db_compiled_xsl file db_root = db_processor.stylesheet.root fw = file(XSLT_COMPILED_FILE, 'wb') cPickle.dump(db_root, fw) # , protocol=2) fw.close()
def __init__(self, stylesheetAltUris=None, documentReader=None, implementation=None, stylesheetIncPaths=None): """ Optional constructor arguments are: stylesheetAltUris: a list of alternative base URIs to use when resolving relative hrefs in xsl:import/xsl:include instructions. These URIs are only tried when the standard XSLT behavior of using the base URI of the xsl:import/include element itself fails to result in retrieval of a document. documentReader: an object that will be used to parse XML source documents (not stylesheets). It defaults to Ft.Xml.Domlette.NonvalidatingReader, but it can be any object that has a parse() method that returns a DOM or Domlette tree. implementation: a DOM implementation instance that will be used by the processor to create new source tree nodes, such as when generating result tree fragments or duplicating the source tree when runNode(node, preserveSrc=1) is called. Defaults to Ft.Xml.Domlette.implementation. Needs to have a createRootNode() method. """ # Calling superclass constructor Processor.__init__(self, stylesheetAltUris=stylesheetAltUris, documentReader=documentReader, implementation=implementation, stylesheetIncPaths=stylesheetIncPaths) Observer.__init__(self) self.first_pass = True self.changed_nodes = [] #the list of the changed nodes. self.last_result = None #the last dom tree generated. self.currentRule = None #a hierachy of reevaluation rules self.our_writer = Dom.CustomDomWriter() #the dom writer
def processDocumentNode( c ): '''this executes the stylesheet node against the current node''' try: if not styleNodeSelected( c ): return proc = Processor() stylenode = stylenodes[ c ] pos = c.p c.selectPosition( stylenode ) sIO = getString( c ) mdom1 = minidom.parseString( sIO ) sIO = str( mdom1.toxml() ) hstring = str( stylenode.h ) if hstring == "": hstring = "no headline" stylesource = InputSource.DefaultFactory.fromString( sIO, uri = hstring) proc.appendStylesheet( stylesource ) c.selectPosition( pos ) xmlnode = pos.v xIO = getString( c ) mdom2 = minidom.parseString( xIO ) xIO = str( mdom2.toxml()) xhead = str( xmlnode.headString ) if xhead == "": xhead = "no headline" xmlsource = InputSource.DefaultFactory.fromString( xIO, uri = xhead ) result = proc.run( xmlsource ) nhline = "xsl:transform of " + str( xmlnode.headString ) p2 = pos.insertAfter() # tnode ) p2.setBodyString(result) p2.setHeadString(nhline) c.redraw() except Exception as x: g.es( 'exception ' + str( x )) c.redraw()
def __init__(self, config, parent): C3Object.__init__(self, config, parent) xfrPath = self.get_path(None, "xsltPath") dfp = self.get_path(None, "defaultPath") path = os.path.join(dfp, xfrPath) xfr = InputSource.DefaultFactory.fromStream(file(path), "file://" + dfp) processor = Processor() processor.appendStylesheet(xfr) self.processor = processor
def runNode(self,DomNode): """ classic XSLT transformation """ self.first_pass = True self.currentRule = None self.our_writer = Dom.CustomDomWriter() Processor.runNode(self,DomNode,writer=self.our_writer) self.last_result = self.our_writer.getResult() self.first_pass = False return self.our_writer.getResult()
def runNode(self, DomNode): """ classic XSLT transformation """ self.first_pass = True self.currentRule = None self.our_writer = Dom.CustomDomWriter() Processor.runNode(self, DomNode, writer=self.our_writer) self.last_result = self.our_writer.getResult() self.first_pass = False return self.our_writer.getResult()
def applyXslt(self, xslStylesheet, topLevelParams=None, extFunctionMap=None, baseUri='file:', styleSheetCache=None): extFunctionMap = extFunctionMap or {} from Ft.Xml.Xslt.Processor import Processor processor = Processor() if styleSheetCache: styleSheet = styleSheetCache.getValue(xslStylesheet, baseUri) processor.appendStylesheetInstance(styleSheet, baseUri) else: processor.appendStylesheet( InputSource.DefaultFactory.fromString( xslStylesheet, baseUri)) #todo: fix baseUri for (k, v) in extFunctionMap.items(): namespace, localName = k processor.registerExtensionFunction(namespace, localName, v) return processor.runNode(self.dom, None, 0, topLevelParams), processor.stylesheet
def transform(xml, xsl): """ A simple wrapper for 4XSLT. """ from Ft.Xml.Xslt.Processor import Processor from Ft.Xml.InputSource import DefaultFactory proc = Processor() xslObj = DefaultFactory.fromString(xsl, "http://rantelope.com/") proc.appendStylesheet(xslObj) xmlObj = DefaultFactory.fromString(xml) return proc.run(xmlObj)
def build_dom_and_apply_style_sheet(self, xsl, file): #doc = xml.dom.minidom.Document() doc = implementation.createRootNode('file:///article.xml') self.app.ann_frame.build_xml(doc) xsltproc = Processor() xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl))) output = xsltproc.runNode(doc, 'file:///article.xml') outFile = open(file,'w') outFile.write(output) outFile.close()
def build_dom_and_apply_style_sheet(self, xsl, file): #doc = xml.dom.minidom.Document() doc = implementation.createRootNode('file:///article.xml') self.app.ann_frame.build_xml(doc) xsltproc = Processor() xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl))) output = xsltproc.runNode(doc, 'file:///article.xml') outFile = open(file, 'w') outFile.write(output) outFile.close()
def GET(self, query_string): try: xml = urllib2.urlopen('http://localhost:8080/marcxml/%s' % query_string).read() xml = InputSource.DefaultFactory.fromString(xml) xslt = InputSource.DefaultFactory.fromUri(XSLT_URIS['mods']) processor = Processor() processor.appendStylesheet(xslt) web.header('Content-Type', 'application/xml') print processor.run(xml) except urllib2.HTTPError, e: if e.code == 404: web.notfound() else: raise
def Test(tester): # We don't use test_harness.XsltTest and friends because they hide away # the API details we're testing in this module. # See http://bugs.4suite.org/641693 tester.startGroup("Test multiple stylesheet invokation") xp = Processor() xp.appendStylesheet( DefaultFactory.fromString(stylesheet_string, uri="data:ss")) result1 = xp.run(DefaultFactory.fromString(source_string, uri="data:src1")) result2 = xp.run(DefaultFactory.fromString(source_string, uri="data:src2")) tester.compare(result1, EXPECTED_1) tester.compare(result2, EXPECTED_1) tester.groupDone() return
def __transform_4suite(self, file, xsl_file, output, params): import codecs from Ft.Xml import InputSource from Ft.Xml.Xslt.Processor import Processor document = InputSource.DefaultFactory.fromUri(file) stylesheet = InputSource.DefaultFactory.fromUri(xsl_file) # there's also a fromString() method processor = Processor() processor.appendStylesheet(stylesheet) result = processor.run(document, topLevelParams=params) (utf8_encode, utf8_decode, utf8_reader, utf8_writer) = codecs.lookup("utf-8") write_obj = utf8_writer(open(output, 'w')) write_obj.write(result) write_obj.close()
def Test(tester): # We don't use test_harness.XsltTest and friends because they hide away # the API details we're testing in this module. # See http://bugs.4suite.org/641693 tester.startGroup("Test multiple stylesheet invokation") xp = Processor() xp.appendStylesheet(DefaultFactory.fromString(stylesheet_string, uri="data:ss")) result1 = xp.run(DefaultFactory.fromString(source_string, uri="data:src1")) result2 = xp.run(DefaultFactory.fromString(source_string, uri="data:src2")) tester.compare(result1, EXPECTED_1) tester.compare(result2, EXPECTED_1) tester.groupDone() return
def get_processor(self, transform_hash, ext_functions=None, ext_elements=None): try: # First make sure we avoid race conditions... self._main_lock.acquire() if transform_hash not in self._granular_locks: self._granular_locks[transform_hash] = thread.allocate_lock() finally: self._main_lock.release() proc = None try: self._granular_locks[transform_hash].acquire() # If we do not have that stylesheet yet in the pool, let's add it if not self._processors.has_key(transform_hash): processor = Processor() self._processors[transform_hash] = processor_info( thread.allocate_lock(), stat(transform_hash)[ST_MTIME], processor ) for (ns, local), func in ext_functions.items(): processor.registerExtensionFunction(ns, local, func) for (ns, local), elem in ext_elements.items(): processor.registerExtensionElement(ns, local, elem) self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash)) # If the stylesheet has been modified, reload it elif stat(transform_hash)[ST_MTIME] != self._processors[transform_hash].last_modified: self._processors[transform_hash].instance.reset() self._processors[transform_hash].last_modified = stat(transform_hash)[ST_MTIME] self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash)) # now we can lock the processor... self._processors[transform_hash]['lock'].acquire() proc = self._processors[transform_hash].instance finally: self._granular_locks[transform_hash].release() # ... and return it return proc
def __init__(self,stream=sys.stdout,encoding='ascii'): XsltProcessor.__init__(self) NodePrinter.__init__(self,stream,encoding) self.writer = codecs.getwriter(encoding)(stream,'xmlcharrefreplace')
def runNode(self,node,nameSpace=EMPTY_NAMESPACE): self.writer.write(codecs.getdecoder('utf-8')(XsltProcessor.runNode(self,node,nameSpace))[0])
for module in map(__import__, modules_to_test): suite.addTest(findTestCases(module)) output, result = XMLTestRunner().run(suite, options.timestamp) ro = output if options.format is not None: try: from Ft.Lib import Uri from Ft.Xml.InputSource import DefaultFactory from Ft.Xml.Xslt.Processor import Processor except: print "Couldn't import modules to generate HTML." processor = Processor() if options.format == "html": xform = DefaultFactory.fromString(html_xform, "uri") elif options.format == "text": xform = DefaultFactory.fromString(text_xform, "uri") processor.appendStylesheet(xform) try: ro = processor.run(DefaultFactory.fromString(output, "uri")) except Exception, e: print "Failed to generate HTML. (%s)" % e ro = None if options.outputFile is not None and ro is not None:
def format(self, formatter): """ Send the text. """ _ = self._ if not self.request.cfg.allow_xslt: from MoinMoin.parser import plain self.request.write(formatter.sysmsg(1) + formatter.text(_('XSLT option disabled!'))+ formatter.sysmsg(0)) plain.Parser(self.raw, self.request).format(formatter) return arena = formatter.page key = 'xslt' cache = caching.CacheEntry(self.request, arena, key) if not cache.needsUpdate(formatter.page._text_filename()): self.request.write(cache.content()) self._add_refresh(formatter, cache, arena, key) return try: # assert we have 4Suite 1.x available from Ft.Xml import __version__ as ft_version assert ft_version.startswith('1.') except (ImportError, AssertionError): self.request.write(self.request.formatter.sysmsg(1) + self.request.formatter.text(_('XSLT processing is not available!')) + self.request.formatter.sysmsg(0)) else: import xml.sax from Ft.Lib import Uri from Ft.Xml import InputSource from Ft.Xml.Xslt.Processor import Processor processor = Processor() msg = None try: base_uri = u'wiki://Self/' # patch broken 4Suite 1.0a1 (announces as "1.0a") # 1.0a3 ("1.0a3") is broken, too # thus, I assume 1.0a2 is also broken and announces either as "1.0a" or "1.0a2", hopefully if ft_version not in ["1.0a", "1.0a2", "1.0a3", "1.0a4",]: # you can add more broken versions here MoinResolver = Uri.SchemeRegistryResolver else: if ft_version == "1.0a4": # 1.0a4 changes location of SchemeRegistryResolver from Ft.Lib import Resolvers SchemeRegistryResolverPATH = Resolvers.SchemeRegistryResolver else: SchemeRegistryResolverPATH = Uri.SchemeRegistryResolver class MoinResolver(SchemeRegistryResolverPATH): def normalize(self, uri, base): from Ft.Lib import Uri if ft_version == "1.0a4": GetSchemeFunc = Uri.GetScheme else: GetSchemeFunc = Uri._getScheme scheme = GetSchemeFunc(uri) if not scheme: if base: scheme = GetSchemeFunc(base) if not scheme: return Uri.BaseUriResolver.normalize(self, uri, base) else: uri = Uri.Absolutize(uri, base) if not uri: return base return uri wiki_resolver = MoinResolver() def _resolve_page(uri, base=None, Uri=Uri, base_uri=base_uri, resolver=wiki_resolver, request=self.request): """ Check whether uri is a valid pagename. """ if uri.startswith(base_uri): pagename = uri[len(base_uri):] page = Page.Page(request, pagename) if page.exists(): return StringIO.StringIO(page.get_raw_body()) else: raise Uri.UriException(Uri.UriException.RESOURCE_ERROR, uri, 'Page does not exist') return Uri.BaseUriResolver.resolve(resolver, uri, base) wiki_resolver.handlers = { 'wiki': _resolve_page, } out_file = StringIO.StringIO() input_factory = InputSource.InputSourceFactory(resolver=wiki_resolver) page_uri = u"%s%s" % (base_uri, formatter.page.page_name) processor.run(input_factory.fromString(self.raw, uri=page_uri), outputStream=out_file) result = out_file.getvalue() except xml.sax.SAXParseException, msg: etype = "SAX" except xml.sax.SAXException, msg: etype = "SAX"
class Parser: """ Send XML file formatted via XSLT. """ caching = 1 Dependencies = Dependencies def __init__(self, raw, request, **kw): self.raw = raw.encode(config.charset) self.request = request self.form = request.form self._ = request.getText self.base_scheme = 'wiki' self.base_uri = 'wiki://Self/' self.key = 'xslt' def format(self, formatter): """ Send the text. """ _ = self._ if not self.request.cfg.allow_xslt: # use plain parser if XSLT is not allowed # can be activated in wikiconfig.py from MoinMoin.parser import plain self.request.write(formatter.sysmsg(1) + formatter.raw_html(_('XSLT option disabled, please look at HelpOnConfiguration.')) + formatter.sysmsg(0)) plain.Parser(self.raw, self.request).format(formatter) return try: # try importing Ft from 4suite # if import fails or its version is not 1.x, error msg from Ft.Xml import __version__ as ft_version assert ft_version.startswith('1.') except (ImportError, AssertionError): self.request.write(self.request.formatter.sysmsg(1) + self.request.formatter.text(_('XSLT processing is not available, please install 4suite 1.x.')) + self.request.formatter.sysmsg(0)) else: from Ft.Lib import Uri from Ft.Xml import InputSource from Ft.Xml.Xslt.Processor import Processor from Ft import FtException msg = None try: # location of SchemeRegisteryResolver has changed since 1.0a4 if ft_version >= "1.0a4": import Ft.Lib.Resolvers # Do not remove! it looks unused, but breaks when removed!!! class MoinResolver(Uri.SchemeRegistryResolver): """ supports resolving self.base_uri for actual pages in MoinMoin """ def __init__(self, handlers, base_scheme): Uri.SchemeRegistryResolver.__init__(self, handlers) self.supportedSchemes.append(base_scheme) # setting up vars for xslt Processor out_file = StringIO.StringIO() wiki_resolver = MoinResolver( handlers={self.base_scheme: self._resolve_page,}, base_scheme=self.base_scheme) input_factory = InputSource.InputSourceFactory(resolver=wiki_resolver) page_name = formatter.page.page_name page_uri = u"%s%s" % (self.base_uri, page_name.encode(config.charset)) raw = self.raw.strip() self.processor = Processor() self.append_stylesheet() # hook, for extending this parser self.processor.run( input_factory.fromString(raw, uri=page_uri), outputStream=out_file) result = out_file.getvalue() result = self.parse_result(result) # hook, for extending this parser except FtException, msg: etype = "XSLT" except Uri.UriException, msg: etype = "XSLT" except IOError, msg: etype = "I/O"
#From Robert Sanderson AKA azaroth42 from Xml.Xslt import test_harness EXPECTED_1 = """<?xml version="1.0" encoding="UTF-8"?>\n""" from Ft.Xml.Xslt.Processor import Processor from Ft.Xml.InputSource import DefaultFactory processor = Processor() TRANSFORM_2 = """<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:template match="/"> <xsl:text>Starting...</xsl:text> <xsl:apply-templates/> <xsl:text>Finished.</xsl:text> </xsl:template> <xsl:template match="aaa"> <xsl:variable name="atxt"> <xsl:value-of select="."/> </xsl:variable> <xsl:if test="atxt='now'"> Now! </xsl:if> </xsl:template> </xsl:stylesheet> """ EXPECTED = 'Starting...Finished.'
def mongetattr(ins, attname): print "Aie!" return None def monset(ins, d): print "On défini un truc sur le contexte" ancienset(ins, d) def monsetattr(ins, attname, val): print "HeHo !" print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys() Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['set'] = monset Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['addDocument'] = monsetattr Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['__setattr__'] = monsetattr print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys() xsltproc = Processor() xsltproc.appendStylesheet( DefaultFactory.fromUri( "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons_to_xhtml_list.xsl" )) html = xsltproc.run( DefaultFactory.fromUri( "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons.xml")) print html
def get_processor(self): proc = Processor() if self.extensions: for ext in self.extensions: proc.registerExtensionFunction(*(ext)) return proc
def format(self, formatter): """ Send the text. """ _ = self._ if not self.request.cfg.allow_xslt: # use plain text parser if XSLT is not allowed # can be activated in wikiconfig.py from MoinMoin.parser.text import Parser as TextParser self.request.write( formatter.sysmsg(1) + formatter.rawHTML( _('XSLT option disabled, please look at HelpOnConfiguration.', wiki=True)) + formatter.sysmsg(0)) TextParser(self.raw, self.request).format(formatter) return try: # try importing Ft from 4suite # if import fails or its version is not 1.x, error msg from Ft.Xml import __version__ as ft_version assert ft_version.startswith('1.') except (ImportError, AssertionError): self.request.write( self.request.formatter.sysmsg(1) + self.request.formatter.text( _('XSLT processing is not available, please install 4suite 1.x.' )) + self.request.formatter.sysmsg(0)) else: from Ft.Lib import Uri from Ft.Xml import InputSource from Ft.Xml.Xslt.Processor import Processor from Ft import FtException msg = None try: # location of SchemeRegisteryResolver has changed since 1.0a4 if ft_version >= "1.0a4" or ft_version == "1.0" or ( "1.0.1" <= ft_version <= "1.0.9"): # such version numbers suck! import Ft.Lib.Resolvers # Do not remove! it looks unused, but breaks when removed!!! class MoinResolver(Uri.SchemeRegistryResolver): """ supports resolving self.base_uri for actual pages in MoinMoin """ def __init__(self, handlers, base_scheme): Uri.SchemeRegistryResolver.__init__(self, handlers) self.supportedSchemes.append(base_scheme) # setting up vars for xslt Processor out_file = StringIO.StringIO() wiki_resolver = MoinResolver(handlers={ self.base_scheme: self._resolve_page, }, base_scheme=self.base_scheme) input_factory = InputSource.InputSourceFactory( resolver=wiki_resolver) page_uri = self.base_uri + wikiutil.url_quote( formatter.page.page_name) # 4Suite needs an utf-8 encoded byte string instead of an unicode object raw = self.raw.strip().encode('utf-8') self.processor = Processor() self.append_stylesheet() # hook, for extending this parser self.processor.run(input_factory.fromString(raw, uri=page_uri), outputStream=out_file) # Convert utf-8 encoded byte string into unicode result = out_file.getvalue().decode('utf-8') result = self.parse_result( result) # hook, for extending this parser except FtException, msg: etype = "XSLT" except Uri.UriException, msg: etype = "XSLT"
def runNode(self,node,nameSpace=EMPTY_NAMESPACE): self.streamWriter.write(codecs.getdecoder(DEFAULT_ENCODING)(XsltProcessor.runNode(self,node,nameSpace))[0])
import Ft from Ft.Xml.InputSource import DefaultFactory import trace,sys from xml.xpath import Context, Util ancienset = Ft.Xml.Xslt.XsltContext.XsltContext.set def mongetattr(ins,attname): print "Aie!" return None def monset(ins,d): print "On défini un truc sur le contexte" ancienset(ins,d) def monsetattr(ins,attname,val): print "HeHo !" print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys() Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['set'] = monset Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['addDocument'] = monsetattr Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['__setattr__'] = monsetattr print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys() xsltproc = Processor() xsltproc.appendStylesheet(DefaultFactory.fromUri("file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons_to_xhtml_list.xsl")) html = xsltproc.run(DefaultFactory.fromUri("file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons.xml")) print html
def format(self, formatter, **kw): """ Send the text. """ _ = self._ if not self.request.cfg.allow_xslt: # use plain text parser if XSLT is not allowed # can be activated in wikiconfig.py from MoinMoin.parser.text import Parser as TextParser self.request.write(formatter.sysmsg(1) + formatter.rawHTML(_('XSLT option disabled, please look at HelpOnConfiguration.', wiki=True)) + formatter.sysmsg(0)) TextParser(self.raw, self.request).format(formatter) return try: # try importing Ft from 4suite # if import fails or its version is not 1.x, error msg from Ft.Xml import __version__ as ft_version assert ft_version.startswith('1.') except (ImportError, AssertionError): self.request.write(self.request.formatter.sysmsg(1) + self.request.formatter.text(_('XSLT processing is not available, please install 4suite 1.x.')) + self.request.formatter.sysmsg(0)) else: from Ft.Lib import Uri from Ft.Xml import InputSource from Ft.Xml.Xslt.Processor import Processor from Ft import FtException msg = None try: # location of SchemeRegisteryResolver has changed since 1.0a4 if ft_version >= "1.0a4" or ft_version == "1.0" or ("1.0.1" <= ft_version <= "1.0.9"): # such version numbers suck! import Ft.Lib.Resolvers # Do not remove! it looks unused, but breaks when removed!!! class MoinResolver(Uri.SchemeRegistryResolver): """ supports resolving self.base_uri for actual pages in MoinMoin """ def __init__(self, handlers, base_scheme): Uri.SchemeRegistryResolver.__init__(self, handlers) self.supportedSchemes.append(base_scheme) # setting up vars for xslt Processor out_file = StringIO.StringIO() wiki_resolver = MoinResolver( handlers={self.base_scheme: self._resolve_page, }, base_scheme=self.base_scheme) input_factory = InputSource.InputSourceFactory(resolver=wiki_resolver) page_uri = self.base_uri + wikiutil.url_quote(formatter.page.page_name) # 4Suite needs an utf-8 encoded byte string instead of an unicode object raw = self.raw.strip().encode('utf-8') self.processor = Processor() self.append_stylesheet() # hook, for extending this parser self.processor.run( input_factory.fromString(raw, uri=page_uri), outputStream=out_file) # Convert utf-8 encoded byte string into unicode result = out_file.getvalue().decode('utf-8') result = self.parse_result(result) # hook, for extending this parser except FtException, msg: etype = "XSLT" except Uri.UriException, msg: etype = "XSLT"
def error(self, message): print "B³±d: " + message def fatal(self, message): print "B³±d krytyczny: " + message # Otwórz pliki HTML i XSTL jako strumienie. html = open('mojblog.html') xsl = open('HTMLnaRSS.xsl') # Przetwórz strumienie i utwórz z nich Ÿród³a wejœciowe. parsedxml = InputSource.DefaultFactory.fromStream(html, "mojblog.html") parsedxsl = InputSource.DefaultFactory.fromStream(xsl, "HTMLnaRSS.xsl") # Utwórz nowy procesor, do³¹cz do niego arkusz stylu a nastêpnie przekszta³æ XML. processor = Processor() processor.appendStylesheet(parsedxsl) HTML = processor.run(parsedxml) # Zapisz wyjœciowy dokument RSS w pliku. output = open("kanalRSS.xml", 'w') output.write(HTML) output.close # Dokonaj walidacji kana³u RSS. parser = xmlval.XMLValidator() parser.set_error_handler(docErrorHandler(parser)) parser.parse_resource("kanalRSS.xml")
def __init__(self,stream=sys.stdout,encoding=DEFAULT_ENCODING): XsltProcessor.__init__(self) NodePrinter.__init__(self,stream,encoding) self.streamWriter = codecs.getwriter(encoding)(stream,'xmlcharrefreplace')