コード例 #1
0
ファイル: DbXslExtension.py プロジェクト: kstaken/Syncato
 def _styleInit(style, uri):        
     if (DbXslExtension.instance == None):
         DbXslExtension.instance = DbXslExtension()
             
     libxslt.registerExtModuleFunction("xpathQuery", uri, DbXslExtension.instance.xpathQuery)
     libxslt.registerExtModuleFunction("deleteRecord", uri, DbXslExtension.instance.deleteRecord)
     libxslt.registerExtModuleFunction("addRecord", uri, DbXslExtension.instance.addRecord)
     libxslt.registerExtModuleFunction("updateRecord", uri, DbXslExtension.instance.updateRecord)
     libxslt.registerExtModuleFunction("getRecord", uri, DbXslExtension.instance.getRecord)
コード例 #2
0
def RegisterXSLTExtensionFunctions():

    libxslt.registerExtModuleFunction("AnniversaryToAirsync",
                                      "http://synce.org/contact",
                                      AnniversaryToAirsync)
    libxslt.registerExtModuleFunction("AnniversaryFromAirsync",
                                      "http://synce.org/contact",
                                      AnniversaryFromAirsync)
    libxslt.registerExtModuleFunction("BirthdayToAirsync",
                                      "http://synce.org/contact",
                                      BirthdayToAirsync)
    libxslt.registerExtModuleFunction("BirthdayFromAirsync",
                                      "http://synce.org/contact",
                                      BirthdayFromAirsync)
コード例 #3
0
            return result

        result = str(temporary_result)

        # Housekeeping
        del temporary_result
        del xslt
        del xsl
        del xml

    elif processor_type == 2:
        # libxml2 & libxslt

        # Register BibFormat functions for use in XSL
        libxslt.registerExtModuleFunction("creation_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_creation_date_libxslt)
        libxslt.registerExtModuleFunction("modification_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_modification_date_libxslt)
        libxslt.registerExtModuleFunction("eval_bibformat",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          eval_bibformat_libxslt)
        # Load template and source
        template_xml = libxml2.parseDoc(template)
        processor = libxslt.parseStylesheetDoc(template_xml)
        source = libxml2.parseDoc(xmltext)

        # Transform
        result_object = processor.applyStylesheet(source, None)
        try:
コード例 #4
0
            print "Invalid parameter specification: '" + sys.argv[count] + "'"
            print usage
            sys.exit(1)
        count = count + 1
except IndexError:
    pass

# ======================================================================
# Memory debug specific
# libxml2.debugMemory(1)

# Setup environment
libxml2.lineNumbersDefault(1)
libxml2.substituteEntitiesDefault(1)
libxslt.registerExtModuleFunction(
    "adjustColumnWidths", "http://nwalsh.com/xslt/ext/xsltproc/python/Table",
    adjustColumnWidths)

# Initialize and run
styledoc = libxml2.parseFile(xslfile)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseFile(xmlfile)
result = style.applyStylesheet(doc, params)

# Save the result
if outfile:
    style.saveResultToFilename(outfile, result, 0)
else:
    print result

# Free things up
コード例 #5
0
ファイル: dbustoany.py プロジェクト: lovesnow/pydbusdecorator
import re
import dbus
import libxslt
import libxml2
from libxml2 import xmlDoc


def replace(ctx, string, pattern, repl, *args, **kwargs):
    return re.sub(pattern, repl, string)


def lower_case(ctx, string, *args, **kwargs):
    return string.lower()


libxslt.registerExtModuleFunction("replace", "https://github.com/hugosenari", replace)
libxslt.registerExtModuleFunction("lower-case", "https://github.com/hugosenari", lower_case)


class XmlHelper(object):
    """
    Class with utilities
    """

    @staticmethod
    def toXmlDoc(xml, *args, **kwargs):
        """
        Converts xml file path or xml str in libxml2.xmlDoc
        """
        result = None
        # test if is xmldoc
コード例 #6
0
def format(xmltext, template_filename=None, template_source=None):
    """
    Processes an XML text according to a template, and returns the result.

    The template can be given either by name (or by path) or by source.
    If source is given, name is ignored.

    bibformat_xslt_engine will look for template_filename in standard directories
    for templates. If not found, template_filename will be assumed to be a path to
    a template. If none can be found, return None.

    @param xmltext: The string representation of the XML to process
    @param template_filename: The name of the template to use for the processing
    @param template_source: The configuration describing the processing.
    @return: the transformed XML text.
    """
    if processor_type == -1:
        # No XSLT processor found
        sys.stderr.write('No XSLT processor could be found.')
        #sys.exit(1)

    # Retrieve template and read it
    if template_source:
        template = template_source
    elif template_filename:
        try:
            path_to_templates = (CFG_BIBFORMAT_TEMPLATES_PATH + os.sep +
                                 template_filename)
            if os.path.exists(path_to_templates):
                template = file(path_to_templates).read()
            elif os.path.exists(template_filename):
                template = file(template_filename).read()
            else:
                sys.stderr.write(template_filename +' does not exist.')
                return None
        except IOError:
            sys.stderr.write(template_filename +' could not be read.')
            return None
    else:
        sys.stderr.write(template_filename +' was not given.')
        return None

    # Some massaging of the input to avoid the default namespace issue
    # in XPath. More elegant solution might be found though.
    xmltext = xmltext.replace('xmlns="http://www.loc.gov/MARC21/slim"', '')

    # For older MARCXML records stored in bibfmt with empty indicators
    xmltext = xmltext.replace('ind1=""', 'ind1=" "')
    xmltext = xmltext.replace('ind2=""', 'ind2=" "')

    result = ""
    if processor_type == 0:
        # libxml2 & libxslt

        # Register BibFormat functions for use in XSL
        libxslt.registerExtModuleFunction("creation_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_creation_date_libxslt)
        libxslt.registerExtModuleFunction("modification_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_modification_date_libxslt)
        libxslt.registerExtModuleFunction("eval_bibformat",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          eval_bibformat_libxslt)
        # Load template and source
        template_xml = libxml2.parseDoc(template)
        processor = libxslt.parseStylesheetDoc(template_xml)
        source = libxml2.parseDoc(xmltext)

        # Transform
        result_object = processor.applyStylesheet(source, None)
        try:
            result = processor.saveResultToString(result_object)
        except SystemError :
            # Catch an exception thrown when result is empty,
            # due to a bug in libxslt
            result = ''

        # Deallocate
        processor.freeStylesheet()
        source.freeDoc()
        result_object.freeDoc()

    elif processor_type == 1:
        # 4suite

        # Init
        processor = Processor.Processor()

        # Register BibFormat functions for use in XSL
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "creation_date",
                                            get_creation_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "modification_date",
                                            get_modification_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "eval_bibformat",
                                            eval_bibformat_4suite)
        # Load template and source
        transform = InputSource.DefaultFactory.fromString(template,
                                                       uri=CFG_SITE_URL)
        source = InputSource.DefaultFactory.fromString(xmltext,
                                                       uri=CFG_SITE_URL)
        processor.appendStylesheet(transform)

        # Transform
        result = processor.run(source)
    else:
        sys.stderr.write("No XSLT processor could be found")

    return result
コード例 #7
0
def format(xmltext, template_filename=None, template_source=None):
    """
    Processes an XML text according to a template, and returns the result.

    The template can be given either by name (or by path) or by source.
    If source is given, name is ignored.

    bibformat_xslt_engine will look for template_filename in standard directories
    for templates. If not found, template_filename will be assumed to be a path to
    a template. If none can be found, return None.

    @param xmltext: The string representation of the XML to process
    @param template_filename: The name of the template to use for the processing
    @param template_source: The configuration describing the processing.
    @return: the transformed XML text.
    """
    if processor_type == -1:
        # No XSLT processor found
        sys.stderr.write('No XSLT processor could be found.')
        #sys.exit(1)

    # Retrieve template and read it
    if template_source:
        template = template_source
    elif template_filename:
        try:
            path_to_templates = (CFG_BIBFORMAT_TEMPLATES_PATH + os.sep +
                                 template_filename)
            if os.path.exists(path_to_templates):
                template = file(path_to_templates).read()
            elif os.path.exists(template_filename):
                template = file(template_filename).read()
            else:
                sys.stderr.write(template_filename + ' does not exist.')
                return None
        except IOError:
            sys.stderr.write(template_filename + ' could not be read.')
            return None
    else:
        sys.stderr.write(template_filename + ' was not given.')
        return None

    # Some massaging of the input to avoid the default namespace issue
    # in XPath. More elegant solution might be found though.
    xmltext = xmltext.replace('xmlns="http://www.loc.gov/MARC21/slim"', '')

    # For older MARCXML records stored in bibfmt with empty indicators
    xmltext = xmltext.replace('ind1=""', 'ind1=" "')
    xmltext = xmltext.replace('ind2=""', 'ind2=" "')

    result = ""
    if processor_type == 0:
        # libxml2 & libxslt

        # Register BibFormat functions for use in XSL
        libxslt.registerExtModuleFunction("creation_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_creation_date_libxslt)
        libxslt.registerExtModuleFunction("modification_date",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          get_modification_date_libxslt)
        libxslt.registerExtModuleFunction("eval_bibformat",
                                          CFG_BIBFORMAT_FUNCTION_NS,
                                          eval_bibformat_libxslt)
        # Load template and source
        template_xml = libxml2.parseDoc(template)
        processor = libxslt.parseStylesheetDoc(template_xml)
        source = libxml2.parseDoc(xmltext)

        # Transform
        result_object = processor.applyStylesheet(source, None)
        try:
            result = processor.saveResultToString(result_object)
        except SystemError:
            # Catch an exception thrown when result is empty,
            # due to a bug in libxslt
            result = ''

        # Deallocate
        processor.freeStylesheet()
        source.freeDoc()
        result_object.freeDoc()

    elif processor_type == 1:
        # 4suite

        # Init
        processor = Processor.Processor()

        # Register BibFormat functions for use in XSL
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "creation_date",
                                            get_creation_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "modification_date",
                                            get_modification_date_4suite)
        processor.registerExtensionFunction(CFG_BIBFORMAT_FUNCTION_NS,
                                            "eval_bibformat",
                                            eval_bibformat_4suite)
        # Load template and source
        transform = InputSource.DefaultFactory.fromString(template,
                                                          uri=CFG_SITE_URL)
        source = InputSource.DefaultFactory.fromString(xmltext,
                                                       uri=CFG_SITE_URL)
        processor.appendStylesheet(transform)

        # Transform
        result = processor.run(source)
    else:
        sys.stderr.write("No XSLT processor could be found")

    return result
コード例 #8
0
    global nodeName

    #
    # Small check to verify the context is correcly accessed
    #
    try:
        pctxt = libxslt.xpathParserContext(_obj=ctx)
        ctxt = pctxt.context()
        tctxt = ctxt.transformContext()
        nodeName = tctxt.insertNode().name
    except:
        pass

    return string.upper(str)

libxslt.registerExtModuleFunction("foo", "http://example.com/foo", f)

styledoc = libxml2.parseDoc("""
<xsl:stylesheet version='1.0'
  xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
  xmlns:foo='http://example.com/foo'
  exclude-result-prefixes='foo'>

  <xsl:param name='bar'>failure</xsl:param>
  <xsl:template match='/'>
    <article><xsl:value-of select='foo:foo($bar)'/></article>
  </xsl:template>
</xsl:stylesheet>
""")
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseDoc("<doc/>")
コード例 #9
0
def convert(xmltext, template_filename=None, template_source=None):
    """
    Processes an XML text according to a template, and returns the result.

    The template can be given either by name (or by path) or by source.
    If source is given, name is ignored.

    bibconvert_xslt_engine will look for template_filename in standard directories
    for templates. If not found, template_filename will be assumed to be a path to
    a template. If none can be found, return None.

    Raises an exception if cannot find an appropriate XSLT processor.


    @param xmltext: The string representation of the XML to process
    @param template_filename: The name of the template to use for the processing
    @param template_source: The configuration describing the processing.
    @return: the transformed XML text, or None if an error occured
    """
    if processor_type == -1:
        # No XSLT processor found
        raise "No XSLT processor could be found"

    # Retrieve template and read it
    if template_source:
        template = template_source
    elif template_filename:
        try:
            path_to_templates = (CFG_BIBCONVERT_XSL_PATH + os.sep +
                                 template_filename)
            if os.path.exists(path_to_templates):
                template = file(path_to_templates).read()
            elif os.path.exists(template_filename):
                template = file(template_filename).read()
            else:
                sys.stderr.write(template_filename +' does not exist.')
                return None
        except IOError:
            sys.stderr.write(template_filename +' could not be read.')
            return None
    else:
        sys.stderr.write(template_filename +' was not given.')
        return None

    result = ""
    if processor_type == 0:
        # libxml2 & libxslt

        # Register BibConvert functions for use in XSL
        libxslt.registerExtModuleFunction("format",
                                          CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_function_libxslt)

        # Load template and source
        try:
            template_xml = libxml2.parseDoc(template)
        except libxml2.parserError, e:
            sys.stderr.write('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')
            return None
        processor = libxslt.parseStylesheetDoc(template_xml)
        try:
            source = libxml2.parseDoc(xmltext)
        except libxml2.parserError, e:
            sys.stderr.write('Parsing XML source failed:\n ' + \
                             str(e) + '\n')
            return None
コード例 #10
0
ファイル: eventconv.py プロジェクト: asmblur/SynCE
def RegisterXSLTExtensionFunctions():

    libxslt.registerExtModuleFunction("TimeTransparencyToAirsync",
                                      "http://synce.org/event",
                                      TimeTransparencyToAirsync)
    libxslt.registerExtModuleFunction("TimeTransparencyFromAirsync",
                                      "http://synce.org/event",
                                      TimeTransparencyFromAirsync)
    libxslt.registerExtModuleFunction("AllDayEventToAirsync",
                                      "http://synce.org/event",
                                      AllDayEventToAirsync)
    libxslt.registerExtModuleFunction("AttendeeToAirsync",
                                      "http://synce.org/event",
                                      AttendeeToAirsync)
    libxslt.registerExtModuleFunction("AttendeeFromAirsync",
                                      "http://synce.org/event",
                                      AttendeeFromAirsync)
    libxslt.registerExtModuleFunction("ExceptionDateTimeToAirsync",
                                      "http://synce.org/event",
                                      ExceptionDateTimeToAirsync)
    libxslt.registerExtModuleFunction("ExceptionDateTimeFromAirsync",
                                      "http://synce.org/event",
                                      ExceptionDateTimeFromAirsync)
コード例 #11
0
ファイル: eventconv.py プロジェクト: asmblur/SynCE
def RegisterXSLTExtensionFunctions():

	libxslt.registerExtModuleFunction("TimeTransparencyToAirsync",   "http://synce.org/event", TimeTransparencyToAirsync)
	libxslt.registerExtModuleFunction("TimeTransparencyFromAirsync", "http://synce.org/event", TimeTransparencyFromAirsync)
	libxslt.registerExtModuleFunction("AllDayEventToAirsync",        "http://synce.org/event", AllDayEventToAirsync)
	libxslt.registerExtModuleFunction("AttendeeToAirsync",           "http://synce.org/event", AttendeeToAirsync)
	libxslt.registerExtModuleFunction("AttendeeFromAirsync",         "http://synce.org/event", AttendeeFromAirsync)
	libxslt.registerExtModuleFunction("ExceptionDateTimeToAirsync",  "http://synce.org/event", ExceptionDateTimeToAirsync)
	libxslt.registerExtModuleFunction("ExceptionDateTimeFromAirsync","http://synce.org/event", ExceptionDateTimeFromAirsync)
コード例 #12
0
            image.seek(0)
            # return image buffer
            return image.read()

        # return unscaled image
        return self.read(path)


# register system:current-time-millis xslt function
def currenttimemillis(ctx):
    # dummy method
    return "0"


libxslt.registerExtModuleFunction(
    "current-time-millis", "http://www.jclark.com/xt/java/java.lang.System", currenttimemillis
)

# load the openoffice.org to html transformation stylesheet
packageDir = Globals.package_home(globals())
__stylefile = packageDir.split(os.sep) + ["converters", "OpenOffice", "sx2ml", "main_html.xsl"]
__stylefile = "/".join(__stylefile)
__styledoc = libxml2.parseFile(__stylefile)
_style = libxslt.parseStylesheetDoc(__styledoc)

# fill new oodocument instances with an empty openoffice.org document
__emptyoodocfile = packageDir.split(os.sep) + ["_EMPTY.sxw"]
__emptyoodocfile = "/".join(__emptyoodocfile)


def loadEmptyOODocument():
コード例 #13
0
ファイル: WeblogXslExtension.py プロジェクト: kstaken/Syncato
    def _styleInit(style, uri):
        if WeblogXslExtension.instance == None:
            WeblogXslExtension.instance = WeblogXslExtension()

        libxslt.registerExtModuleFunction("getConfig", uri, WeblogXslExtension.instance.getConfig)
        libxslt.registerExtModuleFunction("summarize", uri, WeblogXslExtension.instance.summarize)
        libxslt.registerExtModuleFunction("textile", uri, WeblogXslExtension.instance.textileProcess)
        libxslt.registerExtModuleFunction("serialize", uri, WeblogXslExtension.instance.serialize)
        libxslt.registerExtModuleFunction("urlencode", uri, WeblogXslExtension.instance.urlencode)
        libxslt.registerExtModuleFunction("itemlink", uri, WeblogXslExtension.instance.itemLink)
        libxslt.registerExtModuleFunction("normalizeURL", uri, WeblogXslExtension.instance.normalizeURL)

        libxslt.registerExtModuleFunction("previousItem", uri, WeblogXslExtension.instance.previousItem)
        libxslt.registerExtModuleFunction("nextItem", uri, WeblogXslExtension.instance.nextItem)
コード例 #14
0
ファイル: commonconv.py プロジェクト: asmblur/SynCE
def RegisterXSLTExtensionFunctions():

	libxslt.registerExtModuleFunction("HandleOSTZ"           ,     "http://synce.org/common", HandleOSTZ)
	libxslt.registerExtModuleFunction("HandleOSTZComponent"  ,     "http://synce.org/common", HandleOSTZComponent)
	libxslt.registerExtModuleFunction("HandleOSTZRule"       ,     "http://synce.org/common", HandleOSTZRRule)
	libxslt.registerExtModuleFunction("CurrentTZToAirsync"   ,     "http://synce.org/common", CurrentTZToAirsync)
	libxslt.registerExtModuleFunction("TZFromAirsync"   ,          "http://synce.org/common", TZFromAirsync)
	libxslt.registerExtModuleFunction("AllTZToOpensync",           "http://synce.org/common", AllTZToOpensync)
	libxslt.registerExtModuleFunction("OSDateToAirsync"      ,     "http://synce.org/common", OSDateToAirsync)
	libxslt.registerExtModuleFunction("OSDateFromAirsync"    ,     "http://synce.org/common", OSDateFromAirsync)
	libxslt.registerExtModuleFunction("AirsyncDateFromNow"   ,     "http://synce.org/common", AirsyncDateFromNow)
	libxslt.registerExtModuleFunction("OSTextToAirsyncRTF",        "http://synce.org/common", OSTextToAirsyncRTF)
	libxslt.registerExtModuleFunction("OSTextFromAirsyncRTF",      "http://synce.org/common", OSTextFromAirsyncRTF)
	libxslt.registerExtModuleFunction("RecurrenceRuleToAirsync",   "http://synce.org/common", RecurrenceRuleToAirsync)
	libxslt.registerExtModuleFunction("RecurrenceRuleFromAirsync", "http://synce.org/common", RecurrenceRuleFromAirsync)
	libxslt.registerExtModuleFunction("ClassToAirsync",            "http://synce.org/common", ClassToAirsync)
	libxslt.registerExtModuleFunction("ClassFromAirsync",          "http://synce.org/common", ClassFromAirsync)
	libxslt.registerExtModuleFunction("AlarmToAirsync",            "http://synce.org/common", AlarmToAirsync)
	libxslt.registerExtModuleFunction("AlarmFromAirsync",          "http://synce.org/common", AlarmFromAirsync)
コード例 #15
0
ファイル: liblouisxslt.py プロジェクト: IndexBraille/liblouis
    except:
        pass

    typeform = len(str)*[emphasisMap[emphasis]] if emphasis else None
    braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
    return braille.encode('utf-8')

def xsltProcess(styleFile, inputFile, outputFile):
    """Transform an xml inputFile to an outputFile using the given styleFile"""
    styledoc = libxml2.parseFile(styleFile)
    style = libxslt.parseStylesheetDoc(styledoc)
    doc = libxml2.parseFile(inputFile)
    result = style.applyStylesheet(doc, None)
    style.saveResultToFilename(outputFile, result, 0)
    style.freeStylesheet()
    doc.freeDoc()
    result.freeDoc()

libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate)

def main():
    usage = "Usage: %prog [options] styleFile inputFile outputFile"
    parser = OptionParser(usage)
    (options, args) = parser.parse_args()
    if len(args) != 3:
        parser.error("incorrect number of arguments")
    xsltProcess(args[0], args[1], args[2])

if __name__ == "__main__":
    main()
コード例 #16
0
        temporary_result = xslt(xml)

        result = str(temporary_result)

        # Housekeeping
        del temporary_result
        del xslt
        del xsl
        del xml

    elif processor_type == 2:
        # libxml2 & libxslt

        # Register BibConvert functions for use in XSL
        libxslt.registerExtModuleFunction("format", CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_function_libxslt)
        libxslt.registerExtModuleFunction("escape", CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_escape_libxslt)

        # Load template and source
        try:
            template_xml = libxml2.parseDoc(template)
        except libxml2.parserError, e:
            sys.stderr.write('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')
            return None
        processor = libxslt.parseStylesheetDoc(template_xml)
        try:
            source = libxml2.parseDoc(xmltext)
        except libxml2.parserError, e:
            sys.stderr.write('Parsing XML source failed:\n ' + \
コード例 #17
0
def RegisterXSLTExtensionFunctions():

    libxslt.registerExtModuleFunction("DateToAirsyncUTC",
                                      "http://synce.org/task",
                                      DateToAirsyncUTC)
    libxslt.registerExtModuleFunction("DateToAirsyncLocal",
                                      "http://synce.org/task",
                                      DateToAirsyncLocal)
    libxslt.registerExtModuleFunction("DateFromAirsync",
                                      "http://synce.org/task", DateFromAirsync)
    libxslt.registerExtModuleFunction("StatusToAirsync",
                                      "http://synce.org/task", StatusToAirsync)
    libxslt.registerExtModuleFunction("StatusFromAirsync",
                                      "http://synce.org/task",
                                      StatusFromAirsync)
    libxslt.registerExtModuleFunction("PriorityToAirsync",
                                      "http://synce.org/task",
                                      PriorityToAirsync)
    libxslt.registerExtModuleFunction("PriorityFromAirsync",
                                      "http://synce.org/task",
                                      PriorityFromAirsync)
コード例 #18
0
ファイル: xslt_engine.py プロジェクト: mhellmic/b2share
def convert(xmltext, template_filename=None, template_source=None):
    """
    Processes an XML text according to a template, and returns the result.

    The template can be given either by name (or by path) or by source.
    If source is given, name is ignored.

    bibconvert_xslt_engine will look for template_filename in standard directories
    for templates. If not found, template_filename will be assumed to be a path to
    a template. If none can be found, return None.

    Raises an exception if cannot find an appropriate XSLT processor.

    @param xmltext: The string representation of the XML to process
    @param template_filename: The name of the template to use for the processing
    @param template_source: The configuration describing the processing.
    @return: the transformed XML text, or None if an error occured
    """
    if processor_type == 0:
        # No XSLT processor found
        raise "No XSLT processor could be found"

    # Retrieve template and read it
    if template_source:
        template = template_source
    elif template_filename:
        try:
            path_to_templates = templates.get(template_filename, '')
            if os.path.exists(path_to_templates):
                template = file(path_to_templates).read()
            elif os.path.exists(template_filename):
                template = file(template_filename).read()
            else:
                sys.stderr.write(template_filename + ' does not exist.')
                raise Exception(template_filename + ' does not exist.')
        except IOError:
            sys.stderr.write(template_filename + ' could not be read.')
            raise Exception(template_filename + ' could not be read.')
    else:
        sys.stderr.write(template_filename + ' was not given.')
        raise Exception(template_filename + ' was not given.')

    result = ""

    if processor_type == 1:
        # lxml
        try:
            try:
                if(-1 < xmltext.index('?') < 3):
                    xmltext = xmltext[xmltext.index('>')+1:]
            except ValueError:
                #If index() doesn't find the '?' then it raises a useless exception
                pass

            xml = etree.XML(xmltext)
        except etree.XMLSyntaxError as e:
            error = 'The XML code given is invalid. [%s]' % (e,)
            raise Exception(error)
        except Exception as e:
            error = 'Failed to process the XML code.' + str(e)
            raise Exception(error)

        try:
            xsl = etree.XML(template)
        except etree.XMLSyntaxError as e:
            error = 'The XSL code given is invalid. [%s]' % (e,)
            raise Exception(error)
        except Exception as e :
            error = 'Failed to process the XSL code.' + str(e)
            raise Exception(error)

        try:
            fns = etree.FunctionNamespace(CFG_BIBCONVERT_FUNCTION_NS)
            fns["format"] = bibconvert_function_lxml
            fns["escape"] = bibconvert_escape_lxml
        except etree.NamespaceRegistryError as e:
            error = 'Failed registering the XPath extension function. [%s]' % (e,)
            raise Exception(error)

        try:
            xslt = etree.XSLT(xsl)
        except etree.XSLTParseError as e:
            error = 'The XSL code given is invalid. [%s]' % (e,)
            raise Exception(error)
        except:
            error = 'Failed to process the XSL code.'
            raise Exception(error)

        try:
            temporary_result = xslt(xml)
        except:
            error = 'Failed to perform the XSL transformation.'
            raise Exception(error)

        result = str(temporary_result)

        # Housekeeping
        del temporary_result
        del xslt
        del xsl
        del xml

    elif processor_type == 2:
        # libxml2 & libxslt
        # Register BibConvert functions for use in XSL
        libxslt.registerExtModuleFunction("format",
                                          CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_function_libxslt)
        libxslt.registerExtModuleFunction("escape",
                                          CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_escape_libxslt)

        # Load template and source
        try:
            template_xml = libxml2.parseDoc(template)
        except libxml2.parserError as e:
            sys.stderr.write('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')
            raise Exception('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')
        processor = libxslt.parseStylesheetDoc(template_xml)
        try:
            source = libxml2.parseDoc(xmltext)
        except libxml2.parserError as e:
            sys.stderr.write('Parsing XML source failed:\n ' + \
                             str(e) + '\n')
            raise Exception('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')

        # Transform
        result_object = processor.applyStylesheet(source, None)
        result = processor.saveResultToString(result_object)

        # Deallocate
        processor.freeStylesheet()
        source.freeDoc()
        result_object.freeDoc()

    elif processor_type == 3:
        # 4suite
        # Init
        processor = Processor.Processor()

        # Register BibConvert functions for use in XSL
        processor.registerExtensionFunction(CFG_BIBCONVERT_FUNCTION_NS,
                                            "format",
                                            bibconvert_function_4suite)
        processor.registerExtensionFunction(CFG_BIBCONVERT_FUNCTION_NS,
                                          "escape",
                                          bibconvert_escape_4suite)

        # Load template and source
        transform = InputSource.DefaultFactory.fromString(template,
                                                          uri=CFG_SITE_URL)
        source = InputSource.DefaultFactory.fromString(xmltext,
                                                       uri=CFG_SITE_URL)
        try:
            processor.appendStylesheet(transform)
        except XsltException as e:
            sys.stderr.write('Parsing XSL template failed:\n' + str(e))
            raise Exception('Parsing XSL template failed:\n ' +
                            str(e) + '\n')

        # Transform
        try:
            result = processor.run(source)
        except XsltException as e:
            sys.stderr.write('Conversion failed:\n' + str(e))
            raise Exception('Conversion failed:\n' + str(e))
    else:
        sys.stderr.write("No XSLT processor could be found")
        raise Exception("No XSLT processor could be found")
    return result
コード例 #19
0
ファイル: xslt.py プロジェクト: coldwellpacific/variman
            print "Invalid parameter specification: '" + sys.argv[count] + "'"
            print usage
            sys.exit(1);
        count = count+1;
except IndexError:
    pass

# ======================================================================
# Memory debug specific
# libxml2.debugMemory(1)

# Setup environment
libxml2.lineNumbersDefault(1)
libxml2.substituteEntitiesDefault(1)
libxslt.registerExtModuleFunction("adjustColumnWidths",
                                  "http://nwalsh.com/xslt/ext/xsltproc/python/Table",
                                  adjustColumnWidths)

# Initialize and run
styledoc = libxml2.parseFile(xslfile)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseFile(xmlfile)
result = style.applyStylesheet(doc, params)

# Save the result
style.saveResultToFilename(outfile, result, 0)

# Free things up
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()
コード例 #20
0
    return braille.encode('utf-8')


def xsltProcess(styleFile, inputFile, outputFile):
    """Transform an xml inputFile to an outputFile using the given styleFile"""
    styledoc = libxml2.parseFile(styleFile)
    style = libxslt.parseStylesheetDoc(styledoc)
    doc = libxml2.parseFile(inputFile)
    result = style.applyStylesheet(doc, None)
    style.saveResultToFilename(outputFile, result, 0)
    style.freeStylesheet()
    doc.freeDoc()
    result.freeDoc()


libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis",
                                  translate)


def main():
    usage = "Usage: %prog [options] styleFile inputFile outputFile"
    parser = OptionParser(usage)
    (options, args) = parser.parse_args()
    if len(args) != 3:
        parser.error("incorrect number of arguments")
    xsltProcess(args[0], args[1], args[2])


if __name__ == "__main__":
    main()
コード例 #21
0
    return str(random.randint(1, 1000))


def f_exists(ctx, fname):
    return os.path.exists(fname)


def f_max_len(ctx, items):
    print("MAX_LEN", items)
    item0 = items[0]
    print(dir(item0))
    print(str(item0))
    return "no"


libxslt.registerExtModuleFunction(
    "random", "http://arco.esi.uclm.es/commodity", f_random)
libxslt.registerExtModuleFunction(
    "file-exists", "http://arco.esi.uclm.es/commodity", f_exists)
libxslt.registerExtModuleFunction(
    "max-len", "http://arco.esi.uclm.es/commodity", f_max_len)


XSL_DIR = resolve_path('xsl',
                       ['/usr/lib/graf', os.path.dirname(os.path.normpath(__file__))])[0]

logging.info("graf xsl dir: %s", XSL_DIR)


# generar en XML el examen solicitado para el alumno peticionario
def generate_exam(exam_fname, exam_part, answers):
コード例 #22
0
            sys.stderr.write(error)
            return result

        result = str(temporary_result)

        # Housekeeping
        del temporary_result
        del xslt
        del xsl
        del xml

    elif processor_type == 2:
        # libxml2 & libxslt

        # Register BibFormat functions for use in XSL
        libxslt.registerExtModuleFunction("creation_date", CFG_BIBFORMAT_FUNCTION_NS, get_creation_date_libxslt)
        libxslt.registerExtModuleFunction("modification_date", CFG_BIBFORMAT_FUNCTION_NS, get_modification_date_libxslt)
        libxslt.registerExtModuleFunction("eval_bibformat", CFG_BIBFORMAT_FUNCTION_NS, eval_bibformat_libxslt)
        # Load template and source
        template_xml = libxml2.parseDoc(template)
        processor = libxslt.parseStylesheetDoc(template_xml)
        source = libxml2.parseDoc(xmltext)

        # Transform
        result_object = processor.applyStylesheet(source, None)
        try:
            result = processor.saveResultToString(result_object)
        except SystemError:
            # Catch an exception thrown when result is empty,
            # due to a bug in libxslt
            result = ""
コード例 #23
0
ファイル: contactconv.py プロジェクト: asmblur/SynCE
def RegisterXSLTExtensionFunctions():

	libxslt.registerExtModuleFunction("AnniversaryToAirsync",     "http://synce.org/contact", AnniversaryToAirsync)
	libxslt.registerExtModuleFunction("AnniversaryFromAirsync",   "http://synce.org/contact", AnniversaryFromAirsync)
	libxslt.registerExtModuleFunction("BirthdayToAirsync",        "http://synce.org/contact", BirthdayToAirsync)
	libxslt.registerExtModuleFunction("BirthdayFromAirsync",      "http://synce.org/contact", BirthdayFromAirsync)
コード例 #24
0
            return None

        result = str(temporary_result)

        # Housekeeping
        del temporary_result
        del xslt
        del xsl
        del xml

    elif processor_type == 2:
        # libxml2 & libxslt

        # Register BibConvert functions for use in XSL
        libxslt.registerExtModuleFunction("format",
                                          CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_function_libxslt)
        libxslt.registerExtModuleFunction("escape",
                                          CFG_BIBCONVERT_FUNCTION_NS,
                                          bibconvert_escape_libxslt)

        # Load template and source
        try:
            template_xml = libxml2.parseDoc(template)
        except libxml2.parserError, e:
            sys.stderr.write('Parsing XSL template failed:\n ' + \
                             str(e) + '\n')
            return None
        processor = libxslt.parseStylesheetDoc(template_xml)
        try:
            source = libxml2.parseDoc(xmltext)
コード例 #25
0
ファイル: conversions.py プロジェクト: asmblur/SynCE
def register_xslt_extension_functions():
    libxslt.registerExtModuleFunction("contact_has_type",                   "http://synce.org/convert", contact_has_type)
    libxslt.registerExtModuleFunction("contact_position",                   "http://synce.org/convert", contact_position)
    libxslt.registerExtModuleFunction("event_reminder_to_airsync",          "http://synce.org/convert", event_reminder_to_airsync)
    libxslt.registerExtModuleFunction("event_reminder_from_airsync",        "http://synce.org/convert", event_reminder_from_airsync)
    libxslt.registerExtModuleFunction("event_time_to_airsync",           "http://synce.org/convert", event_time_to_airsync)
    libxslt.registerExtModuleFunction("event_datetime_from_airsync",         "http://synce.org/convert", event_datetime_from_airsync)
    libxslt.registerExtModuleFunction("event_datetime_short_from_airsync",   "http://synce.org/convert", event_datetime_short_from_airsync)
    libxslt.registerExtModuleFunction("event_dtstamp_from_now",             "http://synce.org/convert", event_dtstamp_from_now)
    libxslt.registerExtModuleFunction("event_alldayevent_to_airsync",       "http://synce.org/convert", event_alldayevent_to_airsync)
    libxslt.registerExtModuleFunction("event_starttime_from_airsync",       "http://synce.org/convert", event_starttime_from_airsync)
    libxslt.registerExtModuleFunction("event_endtime_from_airsync",         "http://synce.org/convert", event_endtime_from_airsync)
    libxslt.registerExtModuleFunction("event_recurrence_to_airsync",        "http://synce.org/convert", event_recurrence_to_airsync)
    libxslt.registerExtModuleFunction("event_recurrence_from_airsync",      "http://synce.org/convert", event_recurrence_from_airsync)
    libxslt.registerExtModuleFunction("task_start_date_to_airsync",         "http://synce.org/convert", task_start_date_to_airsync)
    libxslt.registerExtModuleFunction("task_due_date_to_airsync",           "http://synce.org/convert", task_due_date_to_airsync)
    libxslt.registerExtModuleFunction("task_start_date_from_airsync",       "http://synce.org/convert", task_start_date_from_airsync)
    libxslt.registerExtModuleFunction("task_due_date_from_airsync",         "http://synce.org/convert", task_due_date_from_airsync)
    libxslt.registerExtModuleFunction("all_description_to_airsync",         "http://synce.org/convert", all_description_to_airsync)
    libxslt.registerExtModuleFunction("all_description_from_airsync",       "http://synce.org/convert", all_description_from_airsync)
    libxslt.registerExtModuleFunction("all_upper_case",                     "http://synce.org/convert", all_upper_case)
コード例 #26
0
ファイル: tzconv.py プロジェクト: asmblur/SynCE
def RegisterXSLTExtensionFunctions():

	libxslt.registerExtModuleFunction("ExtractTZData"          ,"http://synce.org/tz", ExtractTZData)
	libxslt.registerExtModuleFunction("ConvertASTimezoneToVcal","http://synce.org/tz", ConvertASTimezoneToVcal)