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 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 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 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(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 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 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")
class Parser: """ Send XML file formatted via XSLT. """ caching = 1 Dependencies = Dependencies def __init__(self, raw, request, **kw): self.raw = raw 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 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" except IOError, msg: etype = "I/O"
class Parser: """ Send XML file formatted via XSLT. """ caching = 1 Dependencies = Dependencies def __init__(self, raw, request, **kw): self.raw = raw 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, **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" except IOError, msg: etype = "I/O"
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: f = file(options.outputFile, 'w') f.write(ro) f.close() else: if ro is not None: print ro else: print output
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
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): """ 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"
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: f = file(options.outputFile, 'w') f.write(ro) f.close() else: if ro is not None: print ro else: print output