예제 #1
0
def uixml(scwin, uixslt):
    extidx = uixslt.rindex('.')
    xslt2 = uixslt[:extidx] + "Post" + uixslt[extidx:]
    sctemplate = XMLHelper.writexml(scwin.asXML(True), UnicodeStringIO(), '',
                                    '\t', '\n')

    try:
        source = DefaultFactory.fromString(sctemplate, "urn:pass1")
        xsltUri = OsPathToUri(uixslt)
        transform = DefaultFactory.fromUri(xsltUri)

        processor = Processor.Processor()
        processor.appendStylesheet(transform)
        uixmlstr = processor.run(source)

        if os.path.exists(xslt2):
            source = DefaultFactory.fromString(uixmlstr, "urn:pass2")
            xsltUri = OsPathToUri(xslt2)
            transform = DefaultFactory.fromUri(xsltUri)

            processor = Processor.Processor()
            processor.appendStylesheet(transform)
            uixmlstr = processor.run(source)
    except Exception, e:
        QMessageBox.critical(None, 'Error!',
                             'Error with XSLT transform!\n\n' + str(e), 'OK')
        return
예제 #2
0
파일: pipp.py 프로젝트: TheProjecter/pipp
 def processor(self):
     if not self._processor:
         _processor = Processor.Processor(
             stylesheetAltUris=[OsPathToUri(pipp_dir + os.path.sep)])
         _processor.registerExtensionModules(['pipp_xslt'])
         stylesheet = InputSource.DefaultFactory.fromUri(
             OsPathToUri(self.in_root + self.stylesheet_fname))
         _processor.appendStylesheet(stylesheet)
         self._processor = _processor
     return self._processor
예제 #3
0
def pipp_map_view(context, xslt_file):
    ctx = context.processor.extensionParams[(NAMESPACE, 'context')]

    #--
    # Create the XSLT processor object. For efficiency there is a cache of these.
    #--
    xslt_file = ctx.abs_in_path(Conversions.StringValue(xslt_file))
    ctx.add_depends(xslt_file[len(ctx.in_root):])
    processor = processors.get(xslt_file)
    if not processor:
        processor = Processor.Processor()
        processor.registerExtensionModules(['pipp_xslt'])
        processor.appendStylesheet(
            InputSource.DefaultFactory.fromString(
                open(xslt_file).read(), xslt_file))
    processor.extensionParams[(NAMESPACE, 'context')] = ctx

    #--
    # Run the processor against state.xml and return the output.
    # If successful, store the processor object in a cache
    #--
    input = InputSource.DefaultFactory.fromUri(OsPathToUri(ctx.state_xml))
    output = processor.run(input)
    processors[xslt_file] = processor
    return output
    def transform(self, input_filename):
        # load input
        input_uri = OsPathToUri(input_filename)
        input_src = InputSource.DefaultFactory.fromUri(input_uri)

        # transform
        result = self.xslt_processor.run(input_src,
                                         topLevelParams=self.xslt_params)
        return result
예제 #5
0
    def run(self, xslfile, xmlfile, outfile, opts=None, params=None):
        proc = Processor.Processor()
        proc.msgPrefix = ""
        proc.msgSuffix = "\n"
        factory = self.factory

        uri = OsPathToUri(xmlfile)
        xml = factory.fromUri(uri)

        uri = OsPathToUri(xslfile)
        xslt = factory.fromUri(uri, processIncludes=False)

        o = open(outfile, "w")
        proc.appendStylesheet(xslt)
        if params:
            rc = proc.run(xml, outputStream=o, topLevelParams=params)
        else:
            rc = proc.run(xml, outputStream=o)
        o.close()
예제 #6
0
    def parse_dom(self):
        super(XmlQuery, self).parse_dom()
        query_dom = self.dom
        name = query_dom.getAttribute('name')
        if name == '': return

        target = query_dom.getElementsByTagName('target')
        xsl = query_dom.getElementByTagName('xsl')
        if len(target) > 0 and len(xsl) > 0:
            target = target[0]
            xsl = xsl[0]
        else:
            raise Exception(
                "Either a URL or file for XML input must be specified")

        self.processor = Processor.Processor()
        if target.find('://') < 0:
            target = OsPathToUri(target)
        if xsl.find('://') < 0:
            xsl = OsPathToUri(xsl)

        self.target = target
        xsl_source = InputSource.DefaultFactory.fromUri(xsl)
        self.processor.appendStylesheet(transform)

        inputs_dom = query_dom.getElementsByTagName('inputs')
        inputs_dom = [i for i in inputs_dom if i in query_dom.childNodes]

        results_dom = query_dom.getElementsByTagName('results')[0]
        results_inputs_dom = results_dom.getElementsByTagName('inputs')

        self.function = self.find_function(results_dom)

        inputs = Inputs(inputs_dom)

        results_inputs = Inputs(results_inputs_dom)

        self.metadata['target_url'] = target
        self.metadata['xsl'] = xsl
        self.metadata['inputs'] = inputs
        self.metadata['results_inputs'] = results_inputs
        parse_attributes(self.metadata, query_dom)
    def load_xslt(self, xslt_filename):
        # reset processor
        self.xslt_processor.reset()

        # load xslt
        xslt_uri = OsPathToUri(xslt_filename)
        xslt_src = InputSource.DefaultFactory.fromUri(xslt_uri)
        self.xslt_processor.appendStylesheet(xslt_src)

        # reset params
        self.xslt_params.clear()
예제 #8
0
    def parseConfigReport(self, filename, scxmldoc):
        processor = Processor.Processor()
        source = InputSource.DefaultFactory.fromString(
            XMLHelper.writexml(scxmldoc, UnicodeStringIO(), '', '\t', '\n'),
            "uri:sctemplate")

        try:
            xsltUri = OsPathToUri(filename)
            transform = InputSource.DefaultFactory.fromUri(xsltUri)

            processor.appendStylesheet(transform)
            self.reportHtml = processor.run(source)
        except Exception, e:
            QMessageBox.critical(
                None, 'Error!',
                'Error composing report ' + filename + "\n\n" + str(e), 'OK')
            return
예제 #9
0
파일: pipp.py 프로젝트: TheProjecter/pipp
    def __init__(self, in_root, options):

        #--
        # Parse the project definition
        #--
        self.options = options
        self.in_root = in_root.rstrip('/\\')
        self.out_root = os.path.join(self.in_root, 'out')
        self.index = '/index.pip'
        self.stylesheet_fname = '/pipp.xsl'
        self.state_xml = os.path.join(in_root, 'pipp.xml')
        self.changed_exports = []
        self.new_project = not os.path.exists(self.state_xml)
        if self.new_project:
            open(self.state_xml, 'w').write(
                '<page src="%s"><exports><link>%s</link></exports></page>' %
                (self.index, re.sub('.pip$', '.html', self.index)))
        self.state_doc = NonvalidatingReader.parseUri(
            OsPathToUri(self.state_xml))
        self._processor = None
예제 #10
0
def Test(tester):

    source = test_harness.FileInfo(uri="Xml/Xslt/Core/addr_book1.xml")
    sty = test_harness.FileInfo(string=sheet_str_1)
    test_harness.XsltTest(tester,
                          source, [sty],
                          expected_1,
                          title='xsl:include')

    styfactory = InputSourceFactory(resolver=TestResolver())

    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('self-include.xsl'))
    test_harness.XsltTest(tester,
                          source, [sty],
                          None,
                          title='circular xsl:include (direct)',
                          exceptionCode=Error.CIRCULAR_INCLUDE,
                          stylesheetInputFactory=styfactory)

    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('circ-A.xsl'))
    test_harness.XsltTest(tester,
                          source, [sty],
                          None,
                          title='circular xsl:include (indirect)',
                          exceptionCode=Error.CIRCULAR_INCLUDE,
                          stylesheetInputFactory=styfactory)

    # conflicting match templates can raise an exception or produce a result
    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('dup-include-match.xsl'))
    test_harness.XsltTest(
        tester,
        source, [sty],
        'last',
        title='non-circular duplicate include of match templates (direct)',
        exceptionCode=Error.MULTIPLE_MATCH_TEMPLATES,
        stylesheetInputFactory=styfactory)

    # conflicting match templates can raise an exception or produce a result
    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('dup-match.xsl'))
    test_harness.XsltTest(
        tester,
        source, [sty],
        'last',
        title='include of conflicting match templates (direct)',
        exceptionCode=Error.MULTIPLE_MATCH_TEMPLATES,
        stylesheetInputFactory=styfactory)

    # conflicting match templates can raise an exception or produce a result
    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('D.xsl'))
    test_harness.XsltTest(
        tester,
        source, [sty],
        'hello world',
        title='non-circular duplicate include of match templates (indirect)',
        exceptionCode=Error.MULTIPLE_MATCH_TEMPLATES,
        stylesheetInputFactory=styfactory)

    # dup named templates must raise exception
    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('dup-include-named.xsl'))
    test_harness.XsltTest(
        tester,
        source, [sty],
        None,
        title='non-circular duplicate include of named templates (direct)',
        exceptionCode=Error.DUPLICATE_NAMED_TEMPLATE,
        stylesheetInputFactory=styfactory)

    # dup top-level vars must raise exception
    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('dup-include-var.xsl'))
    test_harness.XsltTest(
        tester,
        source, [sty],
        None,
        title='non-circular duplicate include of top-level vars (direct)',
        exceptionCode=Error.DUPLICATE_TOP_LEVEL_VAR,
        stylesheetInputFactory=styfactory)

    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('xinc.xsl'),
                                processIncludes=True)
    test_harness.XsltTest(tester,
                          source, [sty],
                          XINC_EXPECTED_1,
                          title='process XInclude in stylesheet',
                          stylesheetInputFactory=styfactory)

    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('xinc.xsl'),
                                processIncludes=False)
    test_harness.XsltTest(tester,
                          source, [sty],
                          XINC_EXPECTED_2,
                          title='ignore XInclude in stylesheet',
                          stylesheetInputFactory=styfactory)

    source = test_harness.FileInfo(string=DUMMY_XML)
    sty = test_harness.FileInfo(uri=OsPathToUri('circ-xinclude.xsl'),
                                processIncludes=True)
    test_harness.XsltTest(tester,
                          source, [sty],
                          None,
                          title='circular include from XInclude',
                          exceptionCode=Error.STYLESHEET_PARSE_ERROR,
                          stylesheetInputFactory=styfactory)
    return
예제 #11
0
def TreeCompare(expected,
                compared,
                ignoreWhitespace=0,
                baseUri=None,
                readExtDtd=READ_EXTERNAL_DTD,
                ignoreNsDecls=0,
                asEntity=False):
    """
    A cmp()-like function that compares two XML or HTML strings and
    has the side effect of reporting differences to stdout. Returns
    false if the nodes compare equal.

    XML strings are parsed into a Domlette and compared node-by-node.
    HTML strings are parsed with an SGML parser and are compared
    event-by-event. The markup type is guessed based on clues in the
    expected string.

    ignoreWhitespace controls whether whitespace differences in text
    nodes are ignored.

    'file:' URIs based on the current working directory are generated
    for each document. The baseUri argument is an optional absolute URI
    to use as the basis of the generated URIs, if a 'file' URI is
    undesirable.

    readExtDtd controls whether the external DTD subset is read
    when parsing XML. It does not affect the reading of external
    entities declared in the internal DTD subset.

    ignoreNsDecls controls whether namespace declarations are ignored
    when comparing XML documents.
    """
    # See if we need to use XML or HTML
    if not g_xmlTest.match(expected) and g_htmlTest.search(expected):
        return not CompareHTML(expected, compared, ignoreWhitespace)

    if not baseUri:
        uri = OsPathToUri('expected', attemptAbsolute=True)
    else:
        uri = BASIC_RESOLVER.normalize('expected', baseUri)
    try:
        if asEntity:
            reader = Domlette.EntityReader
        elif readExtDtd:
            reader = Domlette.NonvalidatingReader
        else:
            reader = Domlette.NoExtDtdReader

        doc1 = reader.parseString(str(expected), uri)
    except:
        print '--- Expected ---'
        print expected
        raise

    if not baseUri:
        uri = OsPathToUri('expected', attemptAbsolute=True)
    else:
        uri = BASIC_RESOLVER.normalize('compared', baseUri)
    try:
        doc2 = reader.parseString(compared, uri)
    except:
        print '--- Compared ---'
        print compared
        raise

    # If an entity is also a well-formed document entity, remove any
    # top-level whitespace-only text nodes.
    if asEntity:
        _TryEntityAsDocumentEntity(doc1)
        _TryEntityAsDocumentEntity(doc2)

    result = NodeCompare(doc1,
                         doc2,
                         ignoreWhitespace=ignoreWhitespace,
                         ignoreNsDecls=ignoreNsDecls)
    return not result
예제 #12
0
def test_reader(tester, srcReader):
    processor = XUpdate.Processor()

    # ------------------------------------------------------

    tester.startGroup('XUpdate instructions')
    for name, src, xuSrc, expected, vars_ in [
        ("XUpdate spec example 1", src_1, xu_1, expected_1, {}),
        ("Append", src_2, xu_2, expected_2, {}),
        ("Update", src_3, xu_3, expected_3, {}),
        ("Remove", src_4, xu_4, expected_4, {}),
        ("Attribute/Value-Of", src_5, xu_5, expected_5, {
            (None, 'child-name'): "FOO"
        }),
        ("XUpdate spec append example", src_6, xu_6, expected_6, {}),
        ("Append attribute 1", src_7, xu_7, expected_7, {}),
        ("XUpdate use case 4", usecase_src, usecase_4, usecase_expected_4, {}),
        ("Rename", xu_rename_src, xu_rename, rename_expected, {}),
    ]:
        tester.startTest(name)
        uri = OsPathToUri('xupdate-test-src-' + quote(name) + '.xml',
                          attemptAbsolute=True)
        isrc = InputSource.DefaultFactory.fromString(src, uri)
        src = srcReader(isrc)
        uri = OsPathToUri('xupdate-test-xup-' + quote(name) + '.xml',
                          attemptAbsolute=True)
        isrc = InputSource.DefaultFactory.fromString(xuSrc, uri)
        xu = xureader.fromSrc(isrc)

        processor.execute(src, xu, variables=vars_)
        st = cStringIO.StringIO()
        Domlette.Print(src, stream=st)

        tester.compare(expected,
                       st.getvalue(),
                       func=TreeCompare.TreeCompare,
                       diff=True)

        tester.testDone()

    tester.groupDone()

    tester.startGroup('XUpdate exceptions')
    uri = OsPathToUri('xupdate-test-src-2.xml', attemptAbsolute=True)
    isrc = InputSource.DefaultFactory.fromString(src_2, uri)
    src = srcReader(isrc)
    from Ft.Xml.XUpdate import XUpdateException
    for name, xuSrc, expected in [
        ('missing version attr', EXCEPTION_XUP_1, XUpdateException.NO_VERSION),
        ('missing select attr', EXCEPTION_XUP_2, XUpdateException.NO_SELECT),
        ('invalid select attr', EXCEPTION_XUP_3,
         XUpdateException.INVALID_SELECT),
        ('syntax error', EXCEPTION_XUP_4, XUpdateException.SYNTAX_ERROR),
        ('missing test attr', EXCEPTION_XUP_5, XUpdateException.NO_TEST),
        ('unrecognized instruction', EXCEPTION_XUP_6,
         XUpdateException.UNRECOGNIZED_INSTRUCTION),
    ]:
        tester.startTest(name)
        uri = OsPathToUri('xupdate-test-xup-' + quote(name) + '.xml',
                          attemptAbsolute=True)
        isrc = InputSource.DefaultFactory.fromString(xuSrc, uri)
        xu = xureader.fromSrc(isrc)
        tester.testException(processor.execute, (src, xu), XUpdateException,
                             {'errorCode': expected})
        tester.testDone()
    tester.groupDone()

    return
예제 #13
0
#Oliver Graf <*****@*****.**> has indentation probs with ft:write-file

import os, tempfile
from Ft.Lib.Uri import OsPathToUri
from Xml.Xslt import test_harness

BASENAME = tempfile.mktemp()
BASENAME_URI = OsPathToUri(BASENAME)

sheet_1 = """\
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">

<xsl:output method="text" encoding="ISO-8859-1"/>

<xsl:template match="/">
  <xsl:apply-templates select="test/data"/>
</xsl:template>

<xsl:template match="data">
  <xsl:variable name="file" select="concat('%s',.,'.xml')"/>
  <exsl:document href="{$file}" method="xml" indent="yes" encoding="ISO-8859-1">
    <datatree>
      <name><xsl:value-of select="."/></name>
      <what>test</what>
    </datatree>
  </exsl:document>
</xsl:template>
예제 #14
0
import os
from cStringIO import StringIO
from xml.dom import Node

from Ft.Lib.Uri import OsPathToUri, Absolutize
from Ft.Lib.Uuid import GenerateUuid, UuidAsString
from Ft.Xml.Domlette import NonvalidatingReader, implementation, Print
from Ft.Xml.Xvif import RelaxNgValidator, RngInvalid
from Ft.Xml.ThirdParty.Xvif.rng import RngSchemaInvalidException

SPECTEST_ENV_VAR = 'RELAXNG_TEST_SUITE'
SPECTEST_URI = None
if SPECTEST_ENV_VAR in os.environ:
    spectest_path = os.environ[SPECTEST_ENV_VAR]
    SPECTEST_URI = OsPathToUri(spectest_path, attemptAbsolute=True)


def get_description(node):
    sec = node.xpath('section/text()')
    desc = node.xpath('documentation/text()')
    if sec:
        description = 'Section %s' % sec[0].data.encode('us-ascii', 'replace')
    else:
        description = ''
    if desc:
        if sec:
            description += ' - '
        description += desc[0].data.encode('us-ascii', 'replace')
    return description

예제 #15
0
파일: pipp.py 프로젝트: TheProjecter/pipp
    def build(self, force=False, force_children=False):

        # Determine if the timestamp on any dependencies is newer than the output
        if not force:
            abs_output_file = self.abs_out_path(self.abs_in_path(
                self.out_file))
            if os.path.exists(abs_output_file):
                build_time = os.stat(abs_output_file).st_mtime
                deps = [self.file_name] + [
                    get_text(x)
                    for x in self.old_state_node.xpath('depends/depend')
                ]
                changed = any(
                    os.stat(self.abs_in_path(d)).st_mtime > build_time
                    for d in deps)
                if not changed:
                    return False

        if self.project.options.verbose:
            print "Building " + self.file_name

        # Prepare the new state node
        self.state_node = self.state_doc.createElementNS(
            EMPTY_NAMESPACE, 'page')
        self.state_node.setAttributeNS(EMPTY_NAMESPACE, 'src', self.file_name)
        for node_name in [
                'exports', 'links', 'produces', 'depends', 'edepends',
                'children'
        ]:
            new_node = self.project.state_doc.createElementNS(
                EMPTY_NAMESPACE, node_name)
            self.state_node.appendChild(new_node)
            setattr(self, node_name + '_node', new_node)
        self.add_depends(self.project.stylesheet_fname)

        # Run the XSLT processor
        self.old_state_node.parentNode.insertBefore(self.state_node,
                                                    self.old_state_node)
        self.old_state_node.parentNode.removeChild(self.old_state_node)
        try:
            input = InputSource.DefaultFactory.fromUri(
                OsPathToUri(self.project.in_root + self.file_name))
            self.project.processor.extensionParams[(NAMESPACE,
                                                    'context')] = self
            output = self.project.processor.run(input)

            # Spell checking currently disabled
            if 0:  # not self.state_node.xpath('exports/spell'):
                # Check spelling
                pin, pout = os.popen4(
                    '"c:/program files/aspell/bin/aspell" --master=british --home-dir=%s --mode=sgml --rem-sgml-check=alt list'
                    % self.in_root)
                try:
                    pin.write(output)
                except IOError:
                    raise Exception('aspell failed: ' + pout.read())
                pin.close()
                bad_words = pout.read()
                pout.close()
                if bad_words:
                    raise SpellingMistake(
                        "Mispelled words in '%s': %s" %
                        (self.out_file, bad_words), self.out_file,
                        bad_words.split('\n'))

        except:
            self.state_node.parentNode.insertBefore(self.old_state_node,
                                                    self.state_node)
            self.state_node.parentNode.removeChild(self.state_node)
            raise

        # Determine the output file name and write output to it
        abs_output_file = self.abs_out_path(self.abs_in_path(self.out_file))

        dtdnode = self.state_node.xpath('exports/dtd')
        dtd = dtdnode and Conversions.StringValue(dtdnode[0]) or 'strict'
        output_fh = open(abs_output_file, 'w')
        output_fh.write(dtd_defs[dtd] + '\n' + output)
        output_fh.close()

        # Determine if any exported state was changed
        old_exports = dict((x.tagName, get_text(x))
                           for x in self.old_state_node.xpath('exports/*'))
        new_exports = dict((x.tagName, get_text(x))
                           for x in self.state_node.xpath('exports/*'))
        changed = []
        for e in new_exports:
            if new_exports[e] != old_exports.pop(e, None):
                changed.append(e)
        changed += old_exports.keys()
        self.project.changed_exports += [
            '%s:%s' % (self.file_name, c) for c in changed
        ]

        # Determine if the list of children changed
        old_children = [
            Conversions.StringValue(x)
            for x in self.old_state_node.xpath('children/page/@src')
        ]
        new_children = [
            Conversions.StringValue(x)
            for x in self.state_node.xpath('children/page/@src')
        ]
        if old_children != new_children:
            self.project.changed_exports.append('%s:children' % self.file_name)

        # Build children as appropriate
        children_map = dict(
            (x.getAttributeNS(EMPTY_NAMESPACE, 'src'), x)
            for x in self.old_state_node.xpath('children/page'))
        for skel_node in list(self.state_node.xpath('children/page')):
            file_name = skel_node.getAttributeNS(EMPTY_NAMESPACE, 'src')
            full_node = children_map.get(file_name)
            isnew = not bool(full_node)
            if isnew:
                full_node = skel_node
            else:
                skel_node.parentNode.insertBefore(full_node, skel_node)
                skel_node.parentNode.removeChild(skel_node)
            if (isnew or force_children) and file_name.endswith('.pip'):
                PippFile(self.project,
                         full_node).build(force or isnew, force_children)

        return True
예제 #16
0
    usageInfo()
    exit()
    
    
    
print "Converting XML file(s): "+str(currentXMLfiles)+" to "+str(targetFiles)+" using XSL file: "+ currentXSLfile+compileInfo


# Load in source and stylesheet file and transform
processor = Processor.Processor()

ssAsUri = ""
if currentXSLfile.count('http') >0 or currentXSLfile.count('www') > 0:    # web location
    ssAsUri = currentXSLfile
else:
    ssAsUri = OsPathToUri(currentXSLfile)                                # local file
    
transform = InputSource.DefaultFactory.fromUri(ssAsUri)

processor.appendStylesheet(transform)


for i in range(0,len(currentXMLfiles)):

    srcAsUri = OsPathToUri(currentXMLfiles[i])
    source = InputSource.DefaultFactory.fromUri(srcAsUri)

    result = processor.run(source)
    
    out_file = open(targetFiles[i], "w")
    out_file.write(result)
예제 #17
0
def Run(options, args):

    stacktrace_on_error = options.has_key('stacktrace-on-error')

    # -- Set up output streams (will die if files unwritable) ----------
    # (assumes output destinations have been checked for uniqueness)

    if options.has_key('compile'):
        output_flags = "wb"
    else:
        output_flags = "w"

    out_file = options.has_key('outfile') \
               and open(options['outfile'], output_flags) or sys.stdout

    trace_file = None
    if options.has_key('trace'):
        trace_file_name = options.get('trace-file')
        if trace_file_name:
            trace_file_name = os.path.abspath(trace_file_name)

        out_file_name = options.get('outfile')
        if out_file_name:
            out_file_name = os.path.abspath(out_file_name)

        trace_file = options.has_key('trace-file') \
                     and open(options['trace-file'], 'w') or sys.stderr

    # -- Set up XSLT processor (without stylesheets) -------------------

    # gather alt base URIs for xsl:include/import resolution
    #
    # An ordered list of absolute URIs is derived from these sources:
    #  1. command-line option(s) alt-sty-uri=../../foo.xml
    #  2. command-line option(s) alt-sty-path=C:\foo.xml
    #  3. environment variable XSLTINCLUDE=\a\b\foo.xml
    alt_sty_uris = options.get('alt-sty-uri', [])
    if type(alt_sty_uris) != list:
        alt_sty_uris = [alt_sty_uris]

    alt_sty_paths = options.get('alt-sty-path', [])
    if type(alt_sty_paths) != list:
        alt_sty_paths = [alt_sty_paths]

    more_sty_uris = [
        OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths
    ]
    alt_sty_uris.extend(more_sty_uris)

    if os.environ.has_key('XSLTINCLUDE'):
        more_sty_uris = [
            OsPathToUri(path, attemptAbsolute=1)
            for path in os.environ["XSLTINCLUDE"].split(os.pathsep)
        ]
        alt_sty_uris.extend(more_sty_uris)

    del more_sty_uris

    # tracing requires special setup.
    if options.has_key('trace'):
        from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler
        processor = ExtendedProcessingElements.ExtendedProcessor(
            stylesheetAltUris=alt_sty_uris)
        processor._4xslt_trace = True
        processor._4xslt_traceStream = trace_file
        StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings(
        )
    else:
        processor = Processor.Processor(stylesheetAltUris=alt_sty_uris)

    # media prefs affect xsl:stylesheet PI selection
    processor.mediaPref = options.get('media', None)

    # register extension modules
    moduleList = os.environ.get("EXTMODULES")
    if moduleList:
        processor.registerExtensionModules(moduleList.split(":"))

    # set up the source document reader
    from Ft.Xml import Domlette
    validate_flag = options.has_key('validate')
    if validate_flag:
        reader = Domlette.ValidatingReader
    else:
        reader = Domlette.NonvalidatingReader
    processor.setDocumentReader(reader)

    #Customize message behavior
    if options.has_key('no-messages'):
        processor.messageControl(1)
    else:
        processor.messageControl(0)
        if options.has_key('msg-prefix'):
            prefix = options['msg-prefix']
            prefix = prefix.replace('\\n', '\n')
            prefix = prefix.replace('\\r', '\r')
            prefix = prefix.replace('\\t', '\t')
            processor.msgPrefix = prefix
        if options.has_key('msg-suffix'):
            suffix = options['msg-suffix']
            suffix = suffix.replace('\\n', '\n')
            suffix = suffix.replace('\\r', '\r')
            suffix = suffix.replace('\\t', '\t')
            processor.msgSuffix = suffix

    # -- Handle compile operation --------------------------------------

    if options.has_key('compile'):
        xinclude = not options.has_key('noxinclude')
        all_source_args = [args['source-uri']] + args['stylesheet-uri']
        try:
            sty_isrcs = map(
                lambda arg: StySourceArgToInputSource(
                    arg,
                    DefaultFactory,
                    processIncludes=xinclude,
                    stylesheetAltUris=alt_sty_uris), all_source_args)
            for isrc in sty_isrcs:
                processor.appendStylesheet(isrc)
                CloseStream(isrc, quiet=True)

            # use better pickle format in Python 2.3 and up
            if hasattr(cPickle, 'HIGHEST_PROTOCOL'):
                cPickle.dump(processor.stylesheet.root, out_file,
                             cPickle.HIGHEST_PROTOCOL)
            else:
                cPickle.dump(processor.stylesheet.root, out_file, 1)

        except Exception, e:
            ReportFatalException(e, stacktrace_on_error)

        CloseStream(out_file, quiet=True)

        if out_file is sys.stdout:
            dest = 'standard output'
        elif hasattr(out_file, 'name'):
            dest = out_file.name
        elif options.has_key('outfile'):
            dest = options['outfile']
        else:
            dest = 'unknown destination(!)'
        sys.stderr.write('Compiled stylesheet written to %s.\n' % dest)
        sys.stderr.flush()
        return
예제 #18
0
# Oliver Graf <*****@*****.**>:
# ft:output cdata-section-elements is not used

import os, tempfile
from Ft.Lib.Uri import OsPathToUri
from Xml.Xslt import test_harness

FILESTEM = tempfile.mktemp()
FILESTEM_URI = OsPathToUri(FILESTEM)

sheet_1 = """\
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">

<xsl:output method="text" encoding="ISO-8859-1"/>

<xsl:template match="/">
  <xsl:variable name="file" select="'%s'"/>
  <exsl:document href="{$file}" method="xml" indent="yes" encoding="ISO-8859-1"
                 cdata-section-elements="str num">
    <datatree>
      <content><xsl:copy-of select="test/data/*"/></content>
      <what>test</what>
    </datatree>
  </exsl:document>
</xsl:template>

</xsl:stylesheet>"""%(FILESTEM_URI)
예제 #19
0
def Test(tester):
    tester.startTest('Check for DocBook XSL stylesheets')

    dirs = [
        "/usr/share/sgml/docbook/xsl-stylesheets",  #default for docbook-style-xsl RPM
        "/usr/local/share/xsl/docbook",  #default for FreeBSD textproc/docbook-xsl port
    ]

    DOCBOOK_DIR = None
    for dir in dirs:
        if os.path.isdir(dir):
            DOCBOOK_DIR = dir
            break

    DOCBOOK_DIR = os.environ.get(KEYNAME, DOCBOOK_DIR)
    if not DOCBOOK_DIR:
        tester.warning(
            "You need Norm Walsh's DocBook XSL stylesheet package for this test.\n"
            "You can either ignore this, or you can install the DocBook XSL\n"
            "stylesheets and re-run this test. Get the docbook-xsl package from\n"
            "http://sourceforge.net/project/showfiles.php?group_id=21935\n"
            "Install it in anywhere, and then before running this test, set\n"
            "the environment variable %r to the absolute path\n"
            "of the docbook-xsl-#.#.# directory on your filesystem.\n" %
            KEYNAME)
        tester.testDone()
        return

    if not os.path.isdir(DOCBOOK_DIR):
        tester.warning("Unable to find DocBook stylesheet directory %r" %
                       DOCBOOK_DIR)
        tester.testDone()
        return

    VERSION_FILE = os.path.join(DOCBOOK_DIR, 'VERSION')
    if os.path.isfile(VERSION_FILE):
        VERSION = open(VERSION_FILE).read()
        match = re.search(r'>\s*(\d[.0-9]+)\s*<', VERSION)
        if not match:
            tester.warning(
                "Unable to determine version of DocBook stylesheets\n"
                "Format of %r unrecognized." % VERSION_FILE)
            tester.testDone()
            return
        version = match.group(1)
        if version <= MIN_VERSION:
            tester.warning("DocBook XSL version %s or higher needed;"
                           " version %s found." % (MIN_VERSION, version))
            tester.testDone()
            return
    else:
        tester.warning("Unable to determine version of DocBook stylesheets\n"
                       "Was looking for file %r." % VERSION_FILE)
        tester.testDone()
        return

    STYLESHEET = os.path.join(DOCBOOK_DIR, 'html', 'docbook.xsl')
    if not os.path.isfile(STYLESHEET):
        tester.warning("Unable to find DocBook stylesheet %r" % STYLESHEET)
        tester.testDone()
        return

    STYLESHEET_URI = OsPathToUri(STYLESHEET)
    tester.testDone()

    source = test_harness.FileInfo(string=source_1)
    if version >= '1.68':
        expected = expected_1_1680 % version
    else:
        expected = expected_1 % version
    sheet = test_harness.FileInfo(uri=STYLESHEET_URI)
    test_harness.XsltTest(tester,
                          source, [sheet],
                          expected,
                          title="Basic DocBook XSL processing")
    return