pyxsd.schematron

Standalone ISO Schematron compilation, validation, and reporting.

Compile a schema once with compile() or compile(), then validate any number of instances with validate(). The resulting SchematronReport is the native contract: ordered outcomes with XDM node identity, rich messages, diagnostics, properties, and document provenance. It serializes to ISO SVRL, deterministic JSON, or a generic ValidationReport. Validation never converts an operational failure into a report; a caught native error is serialized explicitly with schematron_error_to_svrl().

Resource access is explicit. Compilation and validation each accept their own ResourcePolicy, and validation without one reaches only local files. Compilation and validation budget types, SchematronCompileLimits and SchematronValidationLimits, stay separate.

Submodules

Attributes

Exceptions

SchematronCompileError

A source could not become a Schematron schema.

SchematronError

Base class for every fatal Schematron failure.

SchematronEvaluationError

A validation-time expression, function, key, or document operation failed.

SchematronLimitError

A configured Schematron budget was exhausted.

SchematronSerializationError

One native report or rich-text value has no lossless standard SVRL form.

Classes

SchematronCompileLimits

Optional budgets for resolve, expansion, and expression compilation.

SchematronValidationLimits

Optional budgets for one validation invocation.

ActivePattern

One pattern or group that was active for one document.

DiagnosticMessage

One reusable diagnostic resolved for an outcome.

FiredRule

One rule that matched one context node in one pattern.

MessagePart

One evaluated component of a native Schematron message.

PropertyMessage

One reusable property resolved for an outcome.

SchematronMessage

One check, diagnostic, or property message as native structured parts.

SchematronOutcome

One failed assertion or successful report.

SchematronReport

The immutable result of one native validation.

SchematronSchema

One immutable compiled Schematron schema, safe to share.

Functions

compile(source, *[, query_binding, resource_policy, ...])

Compile one Schematron schema; shorthand for SchematronSchema.compile.

schematron_error_to_svrl(error)

Serialize one caught native error as a grammar-valid svrl:error.

Package Contents

exception pyxsd.schematron.SchematronCompileError(message, *, location=None)

A source could not become a Schematron schema.

location names the exact source occurrence when the failure has one; a well-formedness failure reported by the XML parser has no element occurrence and therefore no location. The rendered message includes the source name, and a known element occurrence adds its line and column.

Parameters:
property location: pyxsd.locations.IssueLocation | None

The source occurrence where the failure was detected, when known.

Return type:

pyxsd.locations.IssueLocation | None

exception pyxsd.schematron.SchematronError

Base class for every fatal Schematron failure.

exception pyxsd.schematron.SchematronEvaluationError(message, *, location=None, schema_location=None, pattern_id=None, rule_id=None, check_id=None, code=None, cause=None, stage=None, document_uri=None, outer_context=None, visited_ordinal=None, visited_item=None)

A validation-time expression, function, key, or document operation failed.

This is an operational failure, never a failed assertion and never a successful report. location names the instance occurrence being evaluated, schema_location the responsible rule, check, or variable declaration, and pattern_id/rule_id/check_id identify the producing definitions when the failure has them. document_uri is the URI of the instance document that owns location, or None when the instance was parsed without one; it is never substituted from the primary document when a visited subordinate supplied the location. stage names the work that failed ("parameters", "let", "visit-each", "phase", "when", "from", "context", "check", "subject", "message", "diagnostic", "property", "flag", "role", "severity", or "documents"), code preserves the original XSLT/XPath error code, and cause retains the original exception. A resource policy’s refusal of a subordinate doc()/document() read is such a failure at any of those stages: cause is that ResourcePolicyError and code is None because no XSLT or XPath error occurred.

outer_context is the structured occurrence of the outer matched rule context, independent of where location points. visited_ordinal and visited_item retain a 2025 @visit-each failure’s item position and bounded display text; they are None when no visited item was in force. visited_item is a display value, not a parsed message field: rewriting the rendered message can never change the structured identity. The explicit svrl:error serializer reads document_uri, location, and code directly. outer_context and the visited fields are typed native identity used to choose the authoritative location; SVRL has no separate slots for them, so its one @location/rich-text pair represents that limit rather than duplicating or reparsing the identities.

Parameters:
location = None
schema_location = None
pattern_id = None
rule_id = None
check_id = None
code = None
cause = None
stage = None
document_uri = None
outer_context = None
visited_ordinal = None
visited_item = None
exception pyxsd.schematron.SchematronLimitError(stage, budget, configured, observed)

A configured Schematron budget was exhausted.

Budget exhaustion is not semantic invalidity: the schema or instance that exceeds a caller’s budget has no verdict. A budget is an inclusive bound, so observing exactly the configured value succeeds and the next unit of work raises. stage names the compiler or validator stage, budget the limit field, configured the caller’s value, and observed the count that crossed it.

Parameters:
property stage: str

The compiler or validator stage that exhausted the budget.

Return type:

str

property budget: str

The limit field name that was exhausted.

Return type:

str

property configured: int

The caller’s configured value for this budget.

Return type:

int

property observed: int

The observed count that exceeded the configured value.

Return type:

int

class pyxsd.schematron.SchematronCompileLimits

Optional budgets for resolve, expansion, and expression compilation.

max_resources counts admitted source resources, including the root. max_expanded_elements counts source elements produced by include, external-extends, and abstract expansion together, so one value bounds the combined work of both stages rather than each stage on its own. max_expressions counts compiled query expressions. A zero budget admits no unit of that work.

max_resources: int | None = None
max_expanded_elements: int | None = None
max_expressions: int | None = None
class pyxsd.schematron.SchematronValidationLimits

Optional budgets for one validation invocation.

max_outcomes bounds retained outcomes; max_sequence_items bounds any single sequence the driver materializes or retains, in particular a rule/@visit-each result and a schema-parameter default. The check happens on the returned sequence’s length before the driver traverses, charges per-item work for, or previews it, so a large selection raises without multiplying work per item or retaining the sequence. The XPath engine still materializes one dispatch’s result; execution.max_steps cannot interrupt work inside that dispatch, so max_sequence_items is the sequence-size bound, not max_steps.

execution carries the XSLT execution budgets used by the expression host. A zero max_outcomes retains no outcome and therefore raises on the first produced outcome; a zero max_sequence_items rejects any non-empty sequence.

max_outcomes: int | None = None
max_sequence_items: int | None = None
execution: pyxsd.xslt.runtime.frames.ExecutionLimits
class pyxsd.schematron.ActivePattern

One pattern or group that was active for one document.

pattern_id is None for an identifier-less container, which can only be active when no phase restricts the active set. origin is the container’s schema occurrence, and document_uri is the URI of the instance document it applied to, when it has one. kind distinguishes an ordinary pattern from a 2025 independent rule group; it defaults to "pattern" for a pre-group constructor call shape. pattern_ordinal is the container’s position in the compiled schema’s native order; one container applied to two documents yields two records that share the ordinal and differ in document_uri.

roots records an effective 2025 phase/@from root set for the original document: None when no phase from applied or when this is an admitted subordinate document, an empty tuple when the original document’s selection was empty (the record stays because the pattern was still active), and otherwise the effective nodes in document order, deduplicated by identity. from never restricts a subordinate document, so a subordinate record always carries None. Every selected root belongs to the original document and lies within any supplied validation subtree.

title, role, and documents_source are the compiled container metadata the 2025 SVRL active-set attributes report: the authored title (including an empty one), the authored role, and the lexical @documents query source. documents_source is not document_uri; it says what the container queried, while the record’s own document_uri says which document this run describes.

pattern_id: str | None
origin: pyxsd.locations.IssueLocation | None
document_uri: str | None
pattern_ordinal: int | None = None
kind: pyxsd.schematron.ir.PatternKind = 'pattern'
roots: tuple[pyxsd.xdm.nodes.XdmNode, ...] | None = None
title: str | None = None
role: str | None = None
documents_source: str | None = None
class pyxsd.schematron.DiagnosticMessage

One reusable diagnostic resolved for an outcome.

id is the authored diagnostic identifier and message its evaluated parts. origin is the diagnostic’s schema occurrence; language and role are the diagnostic’s own metadata, never the referencing check’s.

id: str
message: SchematronMessage
origin: pyxsd.locations.IssueLocation | None
language: str | None
role: str | None
class pyxsd.schematron.FiredRule

One rule that matched one context node in one pattern.

A fired rule is retained even when every check passed or produced no report. context is the matched instance node; node identity, not a path string, distinguishes repeated firings. pattern_ordinal is the producing pattern or group’s position in the compiled schema’s native order, the identity it shares with its active-pattern record and outcomes. visited_count is the number of items the 2025 @visit-each expression selected: None when the rule has no @visit-each, 0 when it selected nothing, and the sequence length otherwise. visited_preview is at most VISITED_PREVIEW_LIMIT leading items, so a firing never retains an unbounded sequence; each outcome still keeps its own visited item. The preview preserves native identity for the serializer, it is not a second copy of the result. The visited items never replace context: the outer matched node remains the rule-selection identity, while each outcome also retains its own visited item.

firing_id is the runtime-assigned identity of this firing within its report. It is a native pairing key, never an authored identifier and never a fabricated SVRL attribute; identifier-less group rules that fire at one node stay distinct through it. visit_each_source is the compiled @visit-each expression text, flag its resolved rule flag token list, and role its resolved rule role.

pattern_id: str | None
rule_id: str | None
context: pyxsd.xdm.nodes.XdmNode
origin: pyxsd.locations.IssueLocation | None
document_uri: str | None
pattern_ordinal: int | None = None
visited_count: int | None = None
visited_preview: tuple[pyxsd.xdm.values.XdmItem, ...] = ()
firing_id: int | None = None
visit_each_source: str | None = None
flag: tuple[str, ...] = ()
role: str | None = None
class pyxsd.schematron.MessagePart

One evaluated component of a native Schematron message.

text is the component’s flattened string value. nodes retains the XDM nodes a value-of or name selected, in selection order. name, attributes, and children describe one markup element; literal text has no nodes or markup. The rule driver’s message expansion fills this model by evaluating compiled parts at the rule focus; serializers read the parts and never reparse or invent content. A selected node from a constructed temporary tree is not a validated instance node: JSON reports instance_node: false with a null path, document URI, and span, and no serializer fabricates a location for it. A node from a foreign parsed document keeps that document’s real URI with instance_node: false and a null path and span: it owns the URI but has no validated instance path.

text: str
nodes: tuple[pyxsd.xdm.nodes.XdmNode, ...] = ()
name: str | None = None
attributes: tuple[tuple[str, str], ...] = ()
children: tuple[MessagePart, ...] = ()
pyxsd.schematron.OutcomeKind
class pyxsd.schematron.PropertyMessage

One reusable property resolved for an outcome.

A property carries a scheme in addition to the diagnostic metadata, and its message may name the context node.

id: str
message: SchematronMessage
origin: pyxsd.locations.IssueLocation | None
language: str | None
role: str | None
scheme: str | None
class pyxsd.schematron.SchematronMessage

One check, diagnostic, or property message as native structured parts.

parts: tuple[MessagePart, ...]
property text: str

The flattened string value of every part, in authored order.

Return type:

str

class pyxsd.schematron.SchematronOutcome

One failed assertion or successful report.

kind distinguishes an assert whose effective boolean value was false from a report whose effective boolean value was true. test is the compiled test’s source text and context the rule’s matched node. subjects holds the subject nodes in selection order: the rule context when neither the check nor the rule declares a subject, an empty tuple for an explicitly empty selection, and every selected node otherwise. primary_subject is the first selected subject, or the rule context when the selection is empty; serializers use it for the generic location without dropping the remaining subjects.

message is the check’s evaluated message, and diagnostics and properties are its referenced reusable messages in authored reference order. flags is the check’s flag token list, inherited from the rule when the check declares none. language, role, severity, see, fpi, and icon are retained as resolved strings; no severity is inferred from a flag, and a 2025 severity never changes the outcome kind, validity, or generic issue severity. pattern_ordinal is the producing pattern or group’s position in the compiled schema’s native order, the identity it shares with its active-pattern record and fired rules.

visited is the 2025 visit-each item whose focus produced this outcome, and visited_ordinal is its zero-based position in the sequence. Both are None for a rule without @visit-each. context always stays the outer matched rule node, so the two identities never collapse. A visited node that belongs to an instance tree supplies the default subject; an atomic item, or a synthetic node with no tree root, supplies no subject and therefore no invented path or byte span. primary_subject still falls back to the real outer context in that case.

firing_id is the runtime-assigned identity of the firing that produced this outcome, the same value carried by its FiredRule. It pairs outcomes with their own firing even when several identifier-less group rules fire at one node; it is never an authored identifier or an SVRL attribute.

kind: OutcomeKind
test: str
context: pyxsd.xdm.nodes.XdmNode
pattern_id: str | None
rule_id: str | None
check_id: str | None
origin: pyxsd.locations.IssueLocation | None
document_uri: str | None
message: SchematronMessage | None = None
subjects: tuple[pyxsd.xdm.nodes.XdmNode, ...] = ()
diagnostics: tuple[DiagnosticMessage, ...] = ()
properties: tuple[PropertyMessage, ...] = ()
flags: tuple[str, ...] = ()
language: str | None = None
role: str | None = None
see: str | None = None
fpi: str | None = None
icon: str | None = None
pattern_ordinal: int | None = None
severity: str | None = None
visited: pyxsd.xdm.values.XdmItem | None = None
visited_ordinal: int | None = None
firing_id: int | None = None
property primary_subject: pyxsd.xdm.nodes.XdmNode

The first subject, or the rule context when none was selected.

Return type:

pyxsd.xdm.nodes.XdmNode

class pyxsd.schematron.SchematronReport

The immutable result of one native validation.

schema and instance are the inputs the report describes; they are excluded from equality and repr so a report compares by its own findings. phase is the phase selector the caller supplied, including a dynamic #ANY token. resolved_phase is the native authored phase that selection actually chose, or None when every pattern ran without a selected phase. SVRL and JSON report the resolved identity; they never serialize a pseudo-selector as a phase name. Outcomes retain production order. is_valid is true exactly when no assertion failed: successful reports never invalidate an instance.

documents holds every instance document this validation owned, in first-seen order: the supplied primary document followed by each distinct admitted subordinate document. It is the native ownership set serializers use to decide whether a message-part or visited node has a real instance location; a constructed temporary tree or foreign document is not in it. Like the inputs, it is excluded from equality and repr.

schema: pyxsd.schematron.ir.CompiledSchema
instance: pyxsd.xdm.nodes.XdmNode
phase: str | None
active_patterns: tuple[ActivePattern, ...]
fired_rules: tuple[FiredRule, ...]
outcomes: tuple[SchematronOutcome, ...]
resolved_phase: str | None = None
documents: tuple[pyxsd.xdm.nodes.XdmDocument, ...] = ()
property failed_assertions: tuple[SchematronOutcome, ...]

Outcomes produced by assertions whose test was false.

Return type:

tuple[SchematronOutcome, …]

property successful_reports: tuple[SchematronOutcome, ...]

Outcomes produced by reports whose test was true.

Return type:

tuple[SchematronOutcome, …]

property is_valid: bool

Whether the instance has no failed assertion.

Return type:

bool

to_validation_report()

Project failed assertions and successful reports to generic issues.

A failed assertion becomes an error with code schematron-failed-assert and a successful report becomes a warning with code schematron-successful-report. The outcome kind alone selects the severity; flag values never do. Each issue points at the outcome’s primary subject and carries the native identifiers, flags, metadata, message, all subjects, diagnostics, and properties in its details.

Return type:

pyxsd.validation.ValidationReport

to_svrl()

Serialize this report as ISO 2025 SVRL.

Serialization reads only the native active-set, fired-rule, and outcome records. No instance text is reparsed, no XSLT is run, and the output contains no generator marker. Firing identity pairs outcomes with their own firing, and a document location is emitted only where the grammar’s anyURI type can represent it.

Return type:

str

to_json()

Serialize this report as deterministic, object-explicit JSON.

The payload states the outcome kind, firing identity, identifiers, flags, link metadata, message parts, subject paths and spans, diagnostics, properties, the caller’s phase selector, the resolved phase identity, document identity, and validity with plain JSON values only.

Return type:

str

class pyxsd.schematron.SchematronSchema(compiled)

One immutable compiled Schematron schema, safe to share.

Construct one with compile() or the module-level compile(). The object stores no per-instance resources or budgets; a validation receives fresh state.

Parameters:

compiled (pyxsd.schematron.ir.CompiledSchema)

classmethod compile(source, *, query_binding=None, resource_policy=None, xml_policy=None, xml_limits=None, limits=None)

Load, resolve, expand, and compile one Schematron schema.

source is a local path, bytes-like object, or readable text/binary stream. A remote reference requires an authorizing resource_policy; without one it is a policy denial rather than a filesystem path.

resource_policy owns reading and parsing the schema and every include, external extends, and XSLT module it names. The whole closure compiles inside the policy’s per-compilation scope, the same scope pyxsd.compile() enters, so a policy that distinguishes a root from a dependency authorizes none of those reads as a fresh root and accounts every one against the same closure budgets. xml_policy and xml_limits configure parsing only when no resource policy is supplied; combining them is rejected before any input is read. They govern the root and every dependency parsed without a policy, so a bound the root satisfies also bounds each include and external extends.

query_binding overrides the authored @queryBinding. limits bounds resource closure, expansion, and expression compilation. Each field is one compile-stage budget: max_expanded_elements counts the elements that includes, external extends, and abstract expansion produce together, so a value every stage fits alone can still be exhausted by their sum. Compile failures raise SchematronError subclasses with the responsible source occurrence where one exists.

Parameters:
Return type:

SchematronSchema

validate(instance, *, phase=None, parameters=None, stylesheet_parameters=None, resource_policy=None, xml_policy=None, xml_limits=None, limits=None)

Validate one instance against this compiled schema.

instance is a raw local path, bytes-like object, or readable stream, an XDM document or subtree, or a captured common Document. Raw input is read once and those admitted bytes are parsed separately by the source index and the XDM builder, plus the supplied policy’s parser when one is present; every view describes the same revision. XDM input passes through unchanged; a common document contributes its coherent to_xdm() tree and is never reparsed. Parser options are rejected for already-parsed input.

phase selects the active patterns. None and #DEFAULT use the schema’s defaultPhase when declared and otherwise activate every pattern; #ALL activates every pattern without phase variables or a phase @from; #ANY evaluates only declared 2025 phase/@when conditions in document order and selects the first true phase, or activates every pattern when none match. Any other value names a declared phase and ignores that phase’s @when. A selected named or default phase may bound the original document’s candidate roots with @from, intersected with any supplied validation subtree; subordinate pattern/@documents documents stay unrestricted. An unknown name raises SchematronEvaluationError with stage="phase".

parameters supplies values for the compiled schema’s top-level sch:param declarations. pyxsd implements the standard’s optional user-supplied value this way: a key must name a declared parameter and a value is a primitive, XDM item, or sequence, converted through the host’s XDM machinery. An undeclared name, an unsupported Python value, or a failed conversion raises SchematronEvaluationError with stage="parameters". Overrides are session-local and never mutate the compiled schema; omitted parameters keep their evaluated defaults.

stylesheet_parameters supplies values for the schema’s top-level library xsl:param declarations, a separate channel from parameters because a schema parameter and an xsl:param can share a lexical name. Keys are the host’s Clark-name, EQName, or lexical-QName parameter names; values pass through the host’s XDM conversion and each declaration’s @as type. An undeclared or static name, a duplicate expanded name, a failed conversion, or a missing required parameter (including an XSLT 3.0 typed parameter with no default) raises SchematronEvaluationError with stage="parameters". Omitted defaulted parameters keep their declared default, and XSLT 2.0 does not apply the XSLT 3.0 implicit-mandatory rule. Bindings are session-local.

resource_policy authorizes raw instances and every subordinate document()/doc()/pattern/@documents read. Compilation authority is never reused, so None reaches only local files. limits bounds retained outcomes and shared execution work; an exhausted limit raises SchematronLimitError and never returns a partial report.

Parameters:
Return type:

pyxsd.schematron.model.SchematronReport

pyxsd.schematron.compile(source, *, query_binding=None, resource_policy=None, xml_policy=None, xml_limits=None, limits=None)

Compile one Schematron schema; shorthand for SchematronSchema.compile.

Every argument has the same meaning as on the class method. The result is immutable and may serve concurrent validations of distinct documents.

Parameters:
Return type:

SchematronSchema

exception pyxsd.schematron.SchematronSerializationError

One native report or rich-text value has no lossless standard SVRL form.

The serializer raises this before returning output for a report with no active pattern or group, records for an undeclared active set, outcomes without their firing rule, ambiguous firings that carry no native identity, a phase value that is not an xsd:NMTOKEN, a malformed flag token list, a subject outside every instance document, or message parts that the SVRL grammar cannot represent. It also rejects characters forbidden by XML 1.0.

pyxsd.schematron.schematron_error_to_svrl(error)

Serialize one caught native error as a grammar-valid svrl:error.

This is the only API that turns an operational failure into SVRL; normal validation never catches an error into a report. The result has the error-only root form the 2025 grammar allows: one root-level svrl:schematron-output with one svrl:error child. Its required @document and @location come from the error’s typed fields, never from its rendered message:

  • a compile error uses its schema occurrence’s source as the document and that occurrence’s element path as the location;

  • an evaluation error uses its owning instance document location and instance location;

  • a limit error, or any error without an occurrence, uses empty values, which the grammar permits only as the genuinely unknown address.

@code is the preserved XSLT/XPath code when one exists. The rendered message is escaped character content of the svrl:error element, not a svrl:text child (the 2025 grammar does not admit one there), and it is never reparsed.

Parameters:

error (pyxsd.schematron.errors.SchematronError)

Return type:

str