# XSLT processing
```{eval-rst}
.. meta::
:description: Run Python-native XSLT 1.0, 2.0, and 3.0 stylesheets with schema-aware XSLT 2.0 and 3.0, XSD or RELAX NG source and target validation, a dedicated CLI, and clean MCP workers.
```
`pyxsd.xslt` is a Python-native XSLT processor with schema-aware XSLT 2.0 and
3.0 profiles. XSD 1.1 types, `xsl:import-schema`, typed XPath expressions, and
source/target validation use the same schema model as pyxsd's Python bindings.
Validation, transformation, and typed object construction stay in one workflow.
This brings a capability often associated with Saxon into a pure-Python XML
stack.
The processor compiles ordinary, simplified, and package stylesheets and runs
them under three explicit processor identities:
- XSLT 3.0 with XPath 3.1, the default `XsltProcessor()`;
- native XSLT 2.0 with XPath 2.0,
`XsltProcessor(language="2.0", xpath="2.0")`;
- native XSLT 1.0 with XPath 1.0,
`XsltProcessor(language="1.0", xpath="1.0")`.
Python callers use {doc}`api` for signatures, {doc}`cli` for the dedicated
command, and {doc}`mcp` for clean-worker previews. {doc}`xml-security` covers
parser, resource, and output boundaries. The measured capability matrix after
the usage sections identifies the selected catalog cases behind each profile;
{doc}`supported` places those results beside the XSD, RELAX NG, and Schematron
capability pages.
## Python: compile once, transform many
`XsltProcessor` is immutable. `compile()` completes the stylesheet or package
closure and every executable expression before it returns a
`CompiledStylesheet`. A static failure raises
{py:class}`~pyxsd.xslt.errors.XsltStaticError`; no partial
artifact is returned. The processor can compile once and run many independent
transformations from the same compiled sheet.
[example: xslt-schemaless]: #
```python
from io import BytesIO
from pyxsd.xslt import XsltProcessor
STYLESHEET = b"""
"""
SOURCE = b''
sheet = XsltProcessor().compile(BytesIO(STYLESHEET))
result = sheet.transform(BytesIO(SOURCE), delivery="document")
document = result.to_document(None)
assert document.to_string() == "2"
assert result.serialize() == "2"
```
`CompiledStylesheet.transform()` accepts a path, bytes-like value, readable
stream, XDM document or subtree, or a common `Document` through its coherent
XDM tree. Omit the source to invoke a named initial template. `parameters`,
`template_parameters`, and `tunnel_parameters` accept XDM values; `limits` takes
an `ExecutionLimits`; `delivery` selects `"stylesheet"`, `"document"`, or
`"raw"`. `output_uri` supplies the absolute base URI for principal and secondary
result identities, and `principal_serialization` overrides principal output
attributes for that invocation.
`CompiledStylesheet.as_transform(target_schema=..., on_result=...)` adapts a
compiled sheet for `Document.transform()`. It runs document delivery over the
document's XDM tree and validates the principal result against the supplied
compiled XSD or RELAX NG schema. Pass `None` for a schemaless result document.
Leave `on_result=None` if the stylesheet produces no secondary results or
messages. If it produces either, supply `on_result` to receive the complete
transformation result.
The complete signatures and defaults are in {doc}`api`.
## JSON in stylesheets
XSLT 3.0 stylesheets can read JSON into XPath maps and arrays with
`parse-json()` and `json-doc()`. `json-to-xml()` produces the standard XML
representation of JSON in `http://www.w3.org/2005/xpath-functions`;
`xml-to-json()` writes that vocabulary back to JSON text. This lets templates
process JSON as XML without imposing an application's XML schema on it.
This example writes a local JSON resource beside its stylesheet, reads it
relative to the stylesheet's base URI, and returns JSON from a named template:
[example: xslt-json]: #
```python
import json
from pathlib import Path
from pyxsd.xslt import XsltProcessor
Path("values.json").write_text('{"values":[1,true,null]}', encoding="utf-8")
stylesheet = Path("json-workflow.xsl")
stylesheet.write_text(
"""
""",
encoding="utf-8",
)
sheet = XsltProcessor().compile(stylesheet)
result = sheet.transform(initial_template="main")
data = json.loads(result.serialize())
assert data["file"] == {"values": [1, True, None]}
assert data["inline"] == data["roundtrip"] == data["file"]
```
`json-doc()` uses the processor's resource policy and runtime resource budgets,
not an unrestricted network fetch. Relative URIs need a stylesheet base URI;
the file-based compilation above supplies one. Configure resource authorization
as described under [namespaces and resolvers](#namespaces-and-resolvers).
`parse-json()` and `json-doc()` accept `liberal`, `duplicates`, `escape`, and
`fallback` options. Duplicate keys default to `use-first`; `use-last` and
`reject` are also available. `json-to-xml()` accepts the same parsing options,
but defaults to retaining duplicate members and accepts `retain`, `use-first`,
or `reject`, not `use-last`. Its `validate=true()` option reports `FOJS0004`;
it does not construct schema-validated JSON-vocabulary nodes.
`escape=true()` cannot be combined with `fallback`. `xml-to-json()` supports
the boolean `indent` option; other options are ignored.
The XPath JSON mapping uses `xs:double` numbers and an empty sequence for JSON
`null`. For Python-native JSON with `int`/`Decimal` numbers, or JSON Schema and
OpenAPI-driven XML mapping, use {doc}`schemaless-data`. For bidirectional JSON
formats derived from an XSD or RELAX NG schema, use {doc}`data-conversion`.
## Command line
The dedicated `pyxsd xslt` command has this syntax (`INPUT` is optional):
```text
pyxsd xslt [options] STYLESHEET [INPUT]
```
`STYLESHEET` is required. An omitted source means the source is absent, which
is valid for a stylesheet that invokes an initial template. `-` reads XML from
stdin; without `-`, an INPUT path is read as XML. `--initial-mode` and
`--source-schema` require INPUT because they need a source document or a source
to validate.
(xslt-workflow-files)=
For the file-based examples, use
{download}`orders.xml <../tests/fixtures/xslt/docs/orders.xml>` and
{download}`summary.xsl <../tests/fixtures/xslt/docs/summary.xsl>`.
For schema validation, also download
{download}`orders.xsd <../tests/fixtures/xslt/docs/orders.xsd>` and
{download}`summary.xsd <../tests/fixtures/xslt/docs/summary.xsd>`, or
{download}`orders.rng <../tests/fixtures/xslt/docs/orders.rng>` and
{download}`summary.rng <../tests/fixtures/xslt/docs/summary.rng>`.
For `report.xsl` invocations, download
{download}`report.xsl <../tests/fixtures/xslt/docs/report.xsl>` and
save {download}`common.xsl <../tests/fixtures/xslt/docs/shared/common.xsl>`
as `shared/common.xsl`.
[example: xslt-cli-validation]: #
```bash
pyxsd xslt summary.xsl orders.xml -o summary.xml
pyxsd xslt summary.xsl - < orders.xml
pyxsd xslt report.xsl orders.xml --initial-template main --param mode=full
pyxsd xslt summary.xsl orders.xml --source-schema orders.xsd \
--target-schema summary.xsd
pyxsd xslt summary.xsl orders.xml --source-schema orders.rng \
--source-schema-format relax-ng --target-schema summary.rng \
--target-schema-format relax-ng
```
`--param` and `--static-param` are repeatable `NAME=VALUE` options. The value is
the parameter's string value, not an XPath expression. A name may be a Clark
name (`{uri}local`), an EQName (`Q{uri}local`), or a lexical QName whose prefix
the principal stylesheet binds. A duplicate name within one channel, or the
same expanded name across the runtime and static channels, is a usage error.
Compilation, static parameters, and the runtime invocation remain separate: a
static parameter can change conditional compilation, while a runtime parameter
only supplies the compiled global.
Output options are `-o PATH` for the principal result, `--result-dir DIR` for
secondary results, `--overwrite`, and `--output-uri URI` as an absolute base
URI. Without `-o`, the principal result is written to stdout. Without
`--result-dir`, secondary results stay in memory and the command prints their
URIs to stderr. With `--result-dir`, every secondary URI maps beneath that
directory; the command rejects traversal, symlinks, non-regular files,
collisions, and an existing destination unless `--overwrite` is set. It
completes serialization and byte-budget checks before publishing any file, so a
serialization failure does not publish a partial principal result.
`--method`, `--encoding`, `--indent`, and `--omit-xml-declaration` override
principal serialization only. Secondary results keep the output attributes
declared in the stylesheet. `--base-uri` sets the source document base; it does
not rewrite the stylesheet base.
Resource and execution controls are explicit:
| Option | Effect |
| --- | --- |
| `--allow-network` | Permit bounded HTTPS retrieval for stylesheet resources and runtime document reads. The default is local-only. |
| `--wall-time SECONDS` | Bound the whole command with an interval timer on the main thread. |
| `--max-frames N` | Bound live execution frames (recursion depth). |
| `--max-steps N` | Bound scheduler dispatches. It does not interrupt work inside one dispatch. |
| `--max-documents N` | Bound runtime documents. |
| `--max-output-nodes N` | Bound principal and secondary result nodes. |
| `--max-output-bytes N` | Bound encoded bytes across delivery and writes. |
| `--max-resource-bytes N` | Bound runtime input bytes and bytes per stylesheet module. |
| `--max-annotations N` | Bound runtime type annotations. |
Each numeric default is the matching `ExecutionLimits` default; `None` in the
library means unlimited, while a CLI option always requires a positive integer.
The output limits are cumulative across nested transforms and writes.
### Source and target validation
`--source-schema` validates the exact admitted source tree before the
stylesheet runs. An invalid source prevents execution and exits `1`; no
transformation result is produced. The source schema must be supplied explicitly
because `--source-schema` is also unavailable without INPUT. A schema that fails
to compile exits `3`.
`--target-schema` validates the principal result as an XML document after the
transformation and before any CLI output is published. An invalid target writes
no CLI output, including no principal stdout and no secondary file, and exits
`1`. A bare atomic value normalizes to a text-only document with no document
element, so target binding fails with `result_shape` and exits `3`. Arrays,
maps, and function items also fail the document-shape check. An atomic value
inside a result element validates normally (`0` or `1`). Target validation does
not apply to secondary results.
`--source-schema-format` and `--target-schema-format` select `xsd` (default) or
`relax-ng` for the corresponding schema. The filename extension never selects
the schema language.
### Exit statuses
| Status | Meaning |
| --- | --- |
| `0` | The command completed, including help output. Validation issues are not fatal unless a validation option makes them so. |
| `1` | A completed source or target validation verdict is invalid. |
| `2` | Argument or usage error. |
| `3` | Stylesheet compilation, schema compilation, transformation, serialization, resource/policy, or I/O error. |
An unreadable stylesheet, source, or schema is a `3`, not a validation verdict.
An invalid source or target is a normal completed verdict and reports the
validation report on stderr.
## MCP previews
`pyxsd_preview_transform` accepts an `XsltTransformSpec` with
`"kind": "xslt"`. The stylesheet runs in a clean worker with the trusted
execution backend set to `disabled`; clean XSLT execution does not require
`--execution-backend trusted-local`. Python and pipeline transform recipes
remain trusted-local: without explicit opt-in they return
`execution_unavailable` and do not fall back to the XSLT path.
Upload `orders.xml`, the two XSD files, `report.xsl`, and
`shared/common.xsl` from the {ref}`XSLT workflow files `. Call
`pyxsd_preview_transform` with the returned workspace ID. The preview
retains `2` and the text `full` as separate artifacts.
The static parameter enables conditional compilation of an `xsl:message`,
so `xslt.messages` contains `{"text": "Debug output", "terminate": false}`.
[example: xslt-mcp-results]: #
```json
{
"workspace_id": "",
"document": {"path": "orders.xml"},
"source_schema": {"source": {"path": "orders.xsd"}},
"target_schema": {"source": {"path": "summary.xsd"}},
"transform": {
"kind": "xslt",
"stylesheet": {"path": "report.xsl"},
"resources": [{"path": "shared/common.xsl"}],
"parameters": {"{urn:example}mode": "full"},
"static_parameters": {"{urn:example}debug": "true"},
"initial_template": null,
"initial_mode": null,
"output_uri": "https://example.test/out/",
"method": "xml",
"encoding": "UTF-8",
"indent": false,
"omit_xml_declaration": true
}
}
```
For XSLT only, `document` and `source_schema` are optional. Omit both to run an
initial-template stylesheet. Python and pipeline recipes require both. There is
no XSLT target=source fallback: when `target_schema` is omitted, no target
validation runs. This differs from Python and pipeline previews, which default
an omitted target to the source schema. When `document` is omitted,
`source_schema` is also invalid because there is no source to validate.
An invalid source is a typed `invalid_source` fault and the transform does not
run. An invalid target is a successful request with `valid=false`: the retained
candidate and its target report remain available for inspection. A target
schema request requires a document element. A bare atomic value produces a
text-only document, which fails target binding with `xslt_validation_error`
and code `result_shape`. Arrays, maps, and function items also fail the shape
check. An atomic value inside a document element validates normally. A non-XML
serialization method reports `well_formed=null`. When an input document exists,
the structural diff artifact reports `available: false`; without an input,
`structural_diff` is null. Only a malformed XML candidate reports
`well_formed=false`, and it has no structural comparison either.
The reply retains exact bytes and references:
- `candidate` is an `ArtifactRef` for the principal result bytes;
- `report` is a JSON sidecar with source and target validation reports;
- `diff` is a byte diff when an input document exists;
- `structural_diff` is the element comparison when both sides are inspectable;
- `xslt.secondary` lists each secondary URI with its own artifact and
serialization, sorted by URI;
- `xslt.serialization` holds the principal serialization;
- `xslt.principal_uri`, `initial_template`, `initial_mode`, and messages describe
the invocation without replacing the artifacts. Transformation warnings are
not exposed by the XSLT preview reply.
`XsltTransformSpec.resources` is the declared closure for `xsl:include`,
`xsl:import`, package modules, and runtime document reads. The worker denies any
read that is not a declared capture entry and denies remote resources; there is
no host or network fallback. Declaring an include is therefore part of preparing
the request, not an optimization. `pyxsd_capabilities` reports
`execution_role: "clean"`, `python_extensions: false`, and the XSLT 1.0, 2.0,
and 3.0 profiles.
The worker validates the captured source and target and returns native
serialized results with bounded reports and sidecars. Validation report issue
lists can be shortened to fit the reply (`suppressed_count` and
`diagnostics_complete` mark that truncation), and structural changes can be
marked `truncated`. A reply that cannot fit its sidecar budget faults rather
than being silently dropped. The coordinator retains artifacts and performs a
rollback when packaging fails after a successful worker reply: it deletes the
candidate, report, diff, structural diff, and secondary artifacts it created for
that request. It does not revalidate the result. That rollback does not delete
artifacts from earlier requests or any source input.
The audit event records `cache=bypass` and an audit-facing `cache_key` computed
from the request, limits, and workspace. **No result cache is implemented**:
the key identifies the operation for audit and invalidation analysis, not a
reusable result. Repeating a request re-executes it.
Schematron uses separate dedicated tools, `pyxsd_schematron_validate` and
`pyxsd_schematron_validate_documents`. It is not a `SchemaRef` format. See
{doc}`mcp` for the request shape, projections, artifacts, and batch independence,
and {doc}`schematron` for the processor contract.
## Source and target validation
The library deliberately keeps transformation and validation separate.
`CompiledStylesheet.transform()` does not validate its source or principal
result. Validate a source before invoking the stylesheet, or validate the result
afterward with `TransformationResult.to_document(schema, uri=...)`.
For XSD:
[example: xslt-xsd]: #
```python
from pyxsd import Schema
from pyxsd.xslt import XsltProcessor
source_schema = Schema.compile("orders.xsd")
target_schema = Schema.compile("summary.xsd")
source = source_schema.parse("orders.xml", capture_xdm=True)
source.require_valid()
sheet = XsltProcessor().compile("summary.xsl")
result = sheet.transform(source, delivery="document")
summary = result.to_document(target_schema)
assert summary.is_valid
assert summary.to_string().strip() == "2"
```
For {doc}`relax-ng`, use the same result API:
[example: xslt-relax-ng]: #
```python
from pyxsd.relaxng import RelaxNGSchema
from pyxsd.xslt import XsltProcessor
source_schema = RelaxNGSchema.compile("orders.rng")
target_schema = RelaxNGSchema.compile("summary.rng")
source = source_schema.parse("orders.xml", capture_xdm=True)
source.require_valid()
result = XsltProcessor().compile("summary.xsl").transform(source, delivery="document")
summary = result.to_document(target_schema)
assert summary.is_valid
assert summary.to_string().strip() == "2"
```
A RELAX NG target has no XSD occurrence annotations on its captured XDM, and target
validation happens on a fresh result-tree view, not by serializing and reparsing
the candidate. `to_document(None)` produces a schemaless document with lexical
typing and a current empty report. A target failure raises `ValidationError`
with the target report.
The CLI and MCP routes apply the same boundaries at their own surfaces: the CLI
validates the admitted source before execution and validates the principal
target before publishing output; MCP validates a captured source before running
and reports a target verdict without hiding the candidate. See {doc}`cli` and
{doc}`mcp`.
## Results and artifacts
`TransformationResult` retains the principal entry, secondary entries, messages,
and warnings. Each `ResultEntry` keeps the raw XDM sequence, the delivered
document tree when one was built, the serialized string when stylesheet delivery
produced one, the effective serialization parameters, character maps, and output
URI.
- `result.principal` is the raw principal XDM sequence.
- `result.principal_tree` returns the delivered tree or a single document-shaped
raw result. It raises `ResultShapeError` instead of wrapping or serializing an
arbitrary sequence.
- `result.secondary` maps absolute result URIs to their entries.
- `result.to_document(schema, uri=None)` binds the principal or selected
secondary result, raising `ValidationError` for an invalid target.
- `result.to_json_document(uri=None)` converts a raw result to an independent
native JSON document.
- `result.serialize(uri=None, parameters=None)` returns a string without
authorization or I/O.
- `result.write(destination, uri=None, parameters=None)` writes after the output
policy authorizes the destination again. Writing spends the same
`max_output_bytes` budget as delivery.
Producing a result performs no file or network write. Secondary results live in
memory until the caller writes them or the CLI or MCP route materializes them.
## Namespaces and resolvers
XSLT namespace bindings come from the stylesheet modules. Elements and
attributes match by expanded name. In Python and MCP, use Clark names
(`{uri}local`) or supported lexical names for static parameter keys. Static
EQNames (`Q{uri}local`) do not currently bind in Python or MCP; runtime EQNames
do. The CLI accepts both Clark names and EQNames for static and runtime
parameters. On the CLI, lexical QNames resolve against the principal
stylesheet root.
`resource_policy` owns stylesheet module loads, includes, imports, and runtime
document reads. `remote_resource_policy` separately authorizes stylesheet-driven
remote runtime reads and must constrain origins, redirects, timeouts, and
consumption.
Supplying a `resource_policy` excludes `xml_policy` and `xml_limits` because the
policy owns parsing. `collection_resolver` supplies `fn:collection` values;
without it, no implicit network collection is fetched.
`resolver` is an explicit package registry. Package modules are registered or
loaded from declared sources; no package is discovered by name, imported from
Python, or fetched from the network. `output_policy` authorizes an absolute
output URI before its content is constructed and authorizes it again on
`TransformationResult.write()`.
## Limits, security, and concurrency
`ExecutionLimits` bounds one transformation and every nested `fn:transform`
call. Nested calls share the cumulative ledger and may narrow but never loosen a
limit. The default `max_frames=100_000` and `max_annotations=262_144`; the other
budgets default to `None`. Budget exhaustion raises an uncatchable
`XsltDynamicError` with code `PYXSD-XSLT-001`, never a partial result. Recursion
depth depends on the interpreter and its version. `max_steps=None` does not stop
an unbounded safe tail recursion; set `max_steps` for such a chain.
XSLT stylesheets are executable code. The library runs them with the caller's
privileges. A resource policy limits what they can read, but it is not a
sandbox; an output policy authorizes destinations, but it does not make the
process safe. Parse stylesheet modules and source documents with an
`XmlParserPolicy` and `XmlLimits` appropriate to untrusted input, or place the
whole operation behind a process boundary with its own timeout.
One compiled stylesheet may run concurrent transformations of distinct inputs.
Each invocation opens its own dynamic context, stacks, globals, result trees,
and budget; compiled static state is immutable. Provider callbacks, resource
policies, output policies, collection resolvers, and Python extensions remain
application code and must be thread-safe if they are shared.
Python extension instructions are a library-only capability registered through
`compile(..., extensions=...)`. MCP reports `python_extensions: false` and
accepts no Python extension registry. The MCP route runs XSLT in a clean worker,
but that worker is not a security sandbox and runs with the server's privileges.
## Packaging
The processor is part of the base `pyxsd` package; no extra is required for
Python or CLI use. The `pyxsd xslt` command is installed with the console
script. The optional MCP route needs the `pyxsd[mcp]` extra, and its wheel and
sdist carry the packaged stylesheet schemas used by advisory inspection.
Compilation itself needs no network access and no external XSLT executable.
## Errors
Static and dynamic failures use the standard XSLT/XPath error identities:
- Import {py:class}`~pyxsd.xslt.errors.XsltStaticError` from `pyxsd.xslt.errors`
to catch compile-time failures such as `XTSE*` and `XPST*`;
- `XsltDynamicError` reports runtime failures such as `XTDE*` and `XTTE*`;
- `XsltInvocationError` reports an invalid host invocation combination;
- `ResultShapeError` reports a requested document view for a non-document
sequence;
- `ValidationError` carries a failed source or target report from
`to_document()` or the document-transform adapter;
- `ResourcePolicyError` reports a policy denial; `PyXSDError` and `OSError` cover
unreadable or malformed input.
The CLI maps invalid source or target verdicts to exit `1`, usage errors to `2`,
and compile, evaluation, policy, shape, serialization, or I/O failures to `3`.
MCP maps faults to typed tool errors and keeps invalid targets as successful
`valid=false` records. The library raises; it does not convert a budget, policy,
or validation failure into a partial result.
```{include} generated/xslt-capabilities.md
```
## Conformance methodology
`tests/xslt/capabilities.py` declares each capability, its profiles, its exact
selected catalog cases, its limitation text, and a public normative reference.
`tests/report_xslt_capabilities.py` loads the pinned catalog and dispositions,
executes every selected case under the declared profile with
`PYXSD_XSLT_OPT=1`, validates the evidence, and renders the fragment above.
`--write` updates it; `--check` regenerates and compares bytes without a
timestamp, host path, or environment-specific order.
A `supported` row requires every selected case to pass. `partial` requires both
a passing and a non-passing selected case. `unsupported` requires explicit
negative evidence and no passing case. `optional-not-claimed` selects no cases
and makes no support or failure claim. The dispositions record reviewed
residuals; the generator never rewrites a failure into a pass.
The selection is bounded. It is not the full XSLT test suite and establishes no
certification, complete feature coverage, streaming behavior, performance, or
identical results on another interpreter or machine. The matrix identifies the
measured profiles and the cases behind each row so a reader can distinguish a
declared profile boundary from a measured defect.
## Examples and source families
Runnable source families live under `examples/`. Each family README owns its
pinned schemas, source downloads, setup, and commands; use those fixtures with
this guide rather than copying paths here. Start at the
[examples index](https://github.com/knorby/pyxsd/blob/develop/examples/README.md),
then follow the relevant README for
[GPX](https://github.com/knorby/pyxsd/blob/develop/examples/gpx/README.md),
[healthcare](https://github.com/knorby/pyxsd/blob/develop/examples/healthcare/README.md),
[CityGML](https://github.com/knorby/pyxsd/blob/develop/examples/citygml/README.md),
[BPMN](https://github.com/knorby/pyxsd/blob/develop/examples/bpmn/README.md),
[OpenDRIVE](https://github.com/knorby/pyxsd/blob/develop/examples/opendrive/README.md),
[XRechnung](https://github.com/knorby/pyxsd/blob/develop/examples/xrechnung/README.md),
or [MusicXML](https://github.com/knorby/pyxsd/blob/develop/examples/musicxml/README.md).
The [data workflows](data-workflows.md) and
[rendering examples](rendering-examples.md) pages route to the same families.