Schematron XML Validation: Assert and Report Elements

ISO Schematron is a structural and business-rule validation language for XML that uses XPath expressions to test documents. Unlike grammar-based schemas like XSD or DTD, Schematron relies on assertions to enforce complex, context-dependent constraints. At the core of ISO Schematron (ISO/IEC 19757-3) are the <assert> and <report> elements, which evaluate XPath expressions against targeted nodes and generate human-readable messages when specific conditions are met or violated.

The Role of Rules and Context

Before validating with <assert> or <report>, Schematron establishes a context using a <rule> element. The context attribute contains an XPath expression matching specific XML elements or attributes.

<pattern id="OrderValidation">
    <rule context="Order">
        <!-- Assert and Report elements go here -->
    </rule>
</pattern>

When a parser processes the XML document, it matches nodes to these rules, and every <assert> and <report> element inside that rule is evaluated relative to that context node.

The <assert> Element: Enforcing Positive Requirements

The <assert> element declares a condition that must be true for the XML to be considered valid. Its test attribute contains an XPath expression evaluating to a boolean value.

<assert test="TotalAmount &gt; 0">
    Error: The TotalAmount for Order <value-of select="@id"/> must be greater than zero.
</assert>

In this example, if TotalAmount is 0 or negative, the test evaluates to false, triggering the error message.

The <report> Element: Catching Prohibited States

The <report> element operates as the logical inverse of <assert>. It declares a condition that must not be true.

<report test="Discount and not(CustomerTier = 'VIP')">
    Warning: A Discount was applied to Order <value-of select="@id"/>, but the customer is not in the VIP tier.
</report>

In this example, if a non-VIP order contains a discount, the test evaluates to true, triggering the report message.

Assert vs. Report: Summary of Differences

Feature <assert> Element <report> Element
Logic Validates that a condition is met. Validates that a condition is not met.
Trigger Event Fires when test is false. Fires when test is true.
Primary Intent Enforcing mandatory requirements. Detecting errors, edge cases, or anti-patterns.

Dynamic Message Construction

Both elements allow dynamic content inside their messages using <value-of select="..."/>. This embeds live data from the XML document into the diagnostic output, making Schematron error reporting precise and actionable for end users.