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¶
A source could not become a Schematron schema. |
|
Base class for every fatal Schematron failure. |
|
A validation-time expression, function, key, or document operation failed. |
|
A configured Schematron budget was exhausted. |
|
One native report or rich-text value has no lossless standard SVRL form. |
Classes¶
Optional budgets for resolve, expansion, and expression compilation. |
|
Optional budgets for one validation invocation. |
|
One pattern or group that was active for one document. |
|
One reusable diagnostic resolved for an outcome. |
|
One rule that matched one context node in one pattern. |
|
One evaluated component of a native Schematron message. |
|
One reusable property resolved for an outcome. |
|
One check, diagnostic, or property message as native structured parts. |
|
One failed assertion or successful report. |
|
The immutable result of one native validation. |
|
One immutable compiled Schematron schema, safe to share. |
Functions¶
|
Compile one Schematron schema; shorthand for |
|
Serialize one caught native error as a grammar-valid |
Package Contents¶
- exception pyxsd.schematron.SchematronCompileError(message, *, location=None)¶
A source could not become a Schematron schema.
locationnames 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:
message (str)
location (pyxsd.locations.IssueLocation | None)
- property location: pyxsd.locations.IssueLocation | None¶
The source occurrence where the failure was detected, when known.
- Return type:
- 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.
locationnames the instance occurrence being evaluated,schema_locationthe responsible rule, check, or variable declaration, andpattern_id/rule_id/check_ididentify the producing definitions when the failure has them.document_uriis the URI of the instance document that ownslocation, orNonewhen the instance was parsed without one; it is never substituted from the primary document when a visited subordinate supplied the location.stagenames the work that failed ("parameters","let","visit-each","phase","when","from","context","check","subject","message","diagnostic","property","flag","role","severity", or"documents"),codepreserves the original XSLT/XPath error code, andcauseretains the original exception. A resource policy’s refusal of a subordinatedoc()/document()read is such a failure at any of those stages:causeis thatResourcePolicyErrorandcodeisNonebecause no XSLT or XPath error occurred.outer_contextis the structured occurrence of the outer matched rule context, independent of wherelocationpoints.visited_ordinalandvisited_itemretain a 2025@visit-eachfailure’s item position and bounded display text; they areNonewhen no visited item was in force.visited_itemis a display value, not a parsed message field: rewriting the rendered message can never change the structured identity. The explicitsvrl:errorserializer readsdocument_uri,location, andcodedirectly.outer_contextand 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:
message (str)
location (pyxsd.locations.IssueLocation | None)
schema_location (pyxsd.locations.IssueLocation | None)
pattern_id (str | None)
rule_id (str | None)
check_id (str | None)
code (str | None)
cause (BaseException | None)
stage (str | None)
document_uri (str | None)
outer_context (pyxsd.locations.IssueLocation | None)
visited_ordinal (int | None)
visited_item (str | None)
- 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.
stagenames the compiler or validator stage,budgetthe limit field,configuredthe caller’s value, andobservedthe count that crossed it.
- class pyxsd.schematron.SchematronCompileLimits¶
Optional budgets for resolve, expansion, and expression compilation.
max_resourcescounts admitted source resources, including the root.max_expanded_elementscounts 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_expressionscounts compiled query expressions. A zero budget admits no unit of that work.
- class pyxsd.schematron.SchematronValidationLimits¶
Optional budgets for one validation invocation.
max_outcomesbounds retained outcomes;max_sequence_itemsbounds any single sequence the driver materializes or retains, in particular arule/@visit-eachresult 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_stepscannot interrupt work inside that dispatch, somax_sequence_itemsis the sequence-size bound, notmax_steps.executioncarries the XSLT execution budgets used by the expression host. A zeromax_outcomesretains no outcome and therefore raises on the first produced outcome; a zeromax_sequence_itemsrejects any non-empty sequence.- execution: pyxsd.xslt.runtime.frames.ExecutionLimits¶
- class pyxsd.schematron.ActivePattern¶
One pattern or group that was active for one document.
pattern_idisNonefor an identifier-less container, which can only be active when no phase restricts the active set.originis the container’s schema occurrence, anddocument_uriis the URI of the instance document it applied to, when it has one.kinddistinguishes an ordinary pattern from a 2025 independent rule group; it defaults to"pattern"for a pre-group constructor call shape.pattern_ordinalis 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 indocument_uri.rootsrecords an effective 2025phase/@fromroot set for the original document:Nonewhen no phasefromapplied 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.fromnever restricts a subordinate document, so a subordinate record always carriesNone. Every selected root belongs to the original document and lies within any supplied validation subtree.title,role, anddocuments_sourceare the compiled container metadata the 2025 SVRL active-set attributes report: the authored title (including an empty one), the authored role, and the lexical@documentsquery source.documents_sourceis notdocument_uri; it says what the container queried, while the record’s owndocument_urisays which document this run describes.- origin: pyxsd.locations.IssueLocation | None¶
- kind: pyxsd.schematron.ir.PatternKind = 'pattern'¶
- roots: tuple[pyxsd.xdm.nodes.XdmNode, ...] | None = None¶
- class pyxsd.schematron.DiagnosticMessage¶
One reusable diagnostic resolved for an outcome.
idis the authored diagnostic identifier andmessageits evaluated parts.originis the diagnostic’s schema occurrence;languageandroleare the diagnostic’s own metadata, never the referencing check’s.- message: SchematronMessage¶
- origin: pyxsd.locations.IssueLocation | 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.
contextis the matched instance node; node identity, not a path string, distinguishes repeated firings.pattern_ordinalis 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_countis the number of items the 2025@visit-eachexpression selected:Nonewhen the rule has no@visit-each,0when it selected nothing, and the sequence length otherwise.visited_previewis at mostVISITED_PREVIEW_LIMITleading 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 replacecontext: the outer matched node remains the rule-selection identity, while each outcome also retains its own visited item.firing_idis 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_sourceis the compiled@visit-eachexpression text,flagits resolved rule flag token list, androleits resolved rule role.- context: pyxsd.xdm.nodes.XdmNode¶
- origin: pyxsd.locations.IssueLocation | None¶
- visited_preview: tuple[pyxsd.xdm.values.XdmItem, ...] = ()¶
- class pyxsd.schematron.MessagePart¶
One evaluated component of a native Schematron message.
textis the component’s flattened string value.nodesretains the XDM nodes avalue-ofornameselected, in selection order.name,attributes, andchildrendescribe 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 reportsinstance_node: falsewith 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 withinstance_node: falseand a null path and span: it owns the URI but has no validated instance path.- nodes: tuple[pyxsd.xdm.nodes.XdmNode, ...] = ()¶
- children: tuple[MessagePart, ...] = ()¶
- pyxsd.schematron.OutcomeKind¶
- class pyxsd.schematron.PropertyMessage¶
One reusable property resolved for an outcome.
A property carries a
schemein addition to the diagnostic metadata, and its message may name the context node.- message: SchematronMessage¶
- origin: pyxsd.locations.IssueLocation | None¶
- class pyxsd.schematron.SchematronMessage¶
One check, diagnostic, or property message as native structured parts.
- parts: tuple[MessagePart, ...]¶
- class pyxsd.schematron.SchematronOutcome¶
One failed assertion or successful report.
kinddistinguishes anassertwhose effective boolean value was false from areportwhose effective boolean value was true.testis the compiled test’s source text andcontextthe rule’s matched node.subjectsholds 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_subjectis 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.messageis the check’s evaluated message, anddiagnosticsandpropertiesare its referenced reusable messages in authored reference order.flagsis the check’s flag token list, inherited from the rule when the check declares none.language,role,severity,see,fpi, andiconare retained as resolved strings; no severity is inferred from a flag, and a 2025severitynever changes the outcome kind, validity, or generic issue severity.pattern_ordinalis 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.visitedis the 2025visit-eachitem whose focus produced this outcome, andvisited_ordinalis its zero-based position in the sequence. Both areNonefor a rule without@visit-each.contextalways 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_subjectstill falls back to the real outercontextin that case.firing_idis the runtime-assigned identity of the firing that produced this outcome, the same value carried by itsFiredRule. 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¶
- context: pyxsd.xdm.nodes.XdmNode¶
- origin: pyxsd.locations.IssueLocation | None¶
- message: SchematronMessage | None = None¶
- subjects: tuple[pyxsd.xdm.nodes.XdmNode, ...] = ()¶
- diagnostics: tuple[DiagnosticMessage, ...] = ()¶
- properties: tuple[PropertyMessage, ...] = ()¶
- visited: pyxsd.xdm.values.XdmItem | None = None¶
- property primary_subject: pyxsd.xdm.nodes.XdmNode¶
The first subject, or the rule context when none was selected.
- Return type:
- class pyxsd.schematron.SchematronReport¶
The immutable result of one native validation.
schemaandinstanceare the inputs the report describes; they are excluded from equality and repr so a report compares by its own findings.phaseis the phase selector the caller supplied, including a dynamic#ANYtoken.resolved_phaseis the native authored phase that selection actually chose, orNonewhen 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_validis true exactly when no assertion failed: successful reports never invalidate an instance.documentsholds 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¶
- active_patterns: tuple[ActivePattern, ...]¶
- outcomes: tuple[SchematronOutcome, ...]¶
- documents: tuple[pyxsd.xdm.nodes.XdmDocument, ...] = ()¶
- property failed_assertions: tuple[SchematronOutcome, ...]¶
Outcomes produced by assertions whose test was false.
- Return type:
- property successful_reports: tuple[SchematronOutcome, ...]¶
Outcomes produced by reports whose test was true.
- Return type:
- to_validation_report()¶
Project failed assertions and successful reports to generic issues.
A failed assertion becomes an error with code
schematron-failed-assertand a successful report becomes a warning with codeschematron-successful-report. The outcome kind alone selects the severity;flagvalues 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 itsdetails.- Return type:
- 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:
- 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:
- class pyxsd.schematron.SchematronSchema(compiled)¶
One immutable compiled Schematron schema, safe to share.
Construct one with
compile()or the module-levelcompile(). 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.
sourceis a local path, bytes-like object, or readable text/binary stream. A remote reference requires an authorizingresource_policy; without one it is a policy denial rather than a filesystem path.resource_policyowns 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 scopepyxsd.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_policyandxml_limitsconfigure 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_bindingoverrides the authored@queryBinding.limitsbounds resource closure, expansion, and expression compilation. Each field is one compile-stage budget:max_expanded_elementscounts 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 raiseSchematronErrorsubclasses with the responsible source occurrence where one exists.- Parameters:
source (SchematronSource)
query_binding (str | None)
resource_policy (pyxsd.resource_policy.ResourcePolicy | None)
xml_policy (pyxsd.xml_policy.XmlParserPolicy | None)
xml_limits (pyxsd.xml_policy.XmlLimits | None)
limits (pyxsd.schematron.limits.SchematronCompileLimits | None)
- Return type:
- 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.
instanceis a raw local path, bytes-like object, or readable stream, an XDM document or subtree, or a captured commonDocument. 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 coherentto_xdm()tree and is never reparsed. Parser options are rejected for already-parsed input.phaseselects the active patterns.Noneand#DEFAULTuse the schema’sdefaultPhasewhen declared and otherwise activate every pattern;#ALLactivates every pattern without phase variables or a phase@from;#ANYevaluates only declared 2025phase/@whenconditions 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; subordinatepattern/@documentsdocuments stay unrestricted. An unknown name raisesSchematronEvaluationErrorwithstage="phase".parameterssupplies values for the compiled schema’s top-levelsch:paramdeclarations. 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 raisesSchematronEvaluationErrorwithstage="parameters". Overrides are session-local and never mutate the compiled schema; omitted parameters keep their evaluated defaults.stylesheet_parameterssupplies values for the schema’s top-level libraryxsl:paramdeclarations, a separate channel fromparametersbecause a schema parameter and anxsl:paramcan 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@astype. 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) raisesSchematronEvaluationErrorwithstage="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_policyauthorizes raw instances and every subordinatedocument()/doc()/pattern/@documentsread. Compilation authority is never reused, soNonereaches only local files.limitsbounds retained outcomes and shared execution work; an exhausted limit raisesSchematronLimitErrorand never returns a partial report.- Parameters:
instance (SchematronSource | pyxsd.xdm.nodes.XdmDocument | pyxsd.xdm.nodes.XdmNode | pyxsd.document.Document)
phase (str | None)
parameters (collections.abc.Mapping[str, Any] | None)
stylesheet_parameters (collections.abc.Mapping[str, Any] | None)
resource_policy (pyxsd.resource_policy.ResourcePolicy | None)
xml_policy (pyxsd.xml_policy.XmlParserPolicy | None)
xml_limits (pyxsd.xml_policy.XmlLimits | None)
limits (pyxsd.schematron.limits.SchematronValidationLimits | None)
- Return type:
- 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:
source (SchematronSource)
query_binding (str | None)
resource_policy (pyxsd.resource_policy.ResourcePolicy | None)
xml_policy (pyxsd.xml_policy.XmlParserPolicy | None)
xml_limits (pyxsd.xml_policy.XmlLimits | None)
limits (pyxsd.schematron.limits.SchematronCompileLimits | None)
- Return type:
- 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-outputwith onesvrl:errorchild. Its required@documentand@locationcome 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.
@codeis the preserved XSLT/XPath code when one exists. The rendered message is escaped character content of thesvrl:errorelement, not asvrl:textchild (the 2025 grammar does not admit one there), and it is never reparsed.- Parameters:
- Return type: