Saxon-HE Python Processor

12.9.0 · active · verified Sun Apr 12

saxonche is the official Saxonica Python wheel package for the SaxonC-HE processor, an XML document processor. It provides APIs to run XSLT 3.0 transformations, XQuery 3.1 queries, XPath 3.1, and XML Schema validation. This library allows Python developers to leverage Saxon's robust and standards-compliant XML processing capabilities, including experimental support for draft 4.0 specifications.

Warnings

Install

Imports

Quickstart

This example demonstrates how to perform an XSLT 3.0 transformation using `saxonche`. It initializes a `PySaxonProcessor`, parses an XML document, compiles an XSLT stylesheet, and then applies the transformation to produce an output string. It uses `license=False` to indicate the open-source Home Edition.

import os
from saxonche import PySaxonProcessor

# Create dummy XML and XSLT files for the example
xml_content = """
<doc>
    <item>Value 1</item>
    <item>Value 2</item>
</doc>
"""
xstl_content = """
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="doc">
        <output>
            <xsl:apply-templates select="item"/>
        </output>
    </xsl:template>
    <xsl:template match="item">
        <transformed-item>
            <xsl:value-of select="."/>
        </transformed-item>
    </xsl:template>
</xsl:stylesheet>
"""

with open("input.xml", "w") as f:
    f.write(xml_content)
with open("transform.xsl", "w") as f:
    f.write(xstl_content)

try:
    # Initialize Saxon processor (license=False for open-source HE edition)
    with PySaxonProcessor(license=False) as proc:
        print(f"SaxonC Version: {proc.version()}")

        # Create XSLT 3.0 processor
        xslt_processor = proc.new_xslt30_processor()

        # Parse XML source document
        input_document = proc.parse_xml(xml_file_name="input.xml")
        if not input_document:
            print(f"Error parsing XML: {proc.error_message()}")
            exit(1)

        # Compile XSLT stylesheet
        stylesheet = xslt_processor.compile_stylesheet(stylesheet_file="transform.xsl")
        if not stylesheet:
            print(f"Error compiling XSLT: {xslt_processor.error_message()}")
            exit(1)

        # Perform transformation
        output = stylesheet.transform_to_string(xdm_node=input_document)
        if not output:
            print(f"Error during transformation: {xslt_processor.error_message()}")
            exit(1)

        print("Transformation Output:")
        print(output)

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up dummy files
    if os.path.exists("input.xml"):
        os.remove("input.xml")
    if os.path.exists("transform.xsl"):
        os.remove("transform.xsl")

view raw JSON →