Rule-Based XML Validation with Schematron and XPath

This article provides an overview of Schematron, an ISO-standard validation language designed to enforce complex business rules in XML documents using XPath expressions. Readers will learn how Schematron differs from traditional grammar-based XML schemas, how its core components function, and how XPath enables precise context selection and conditional validation to produce custom, human-readable error reports.

What is Schematron?

Schematron is a structural and rule-based validation language for XML. Unlike traditional grammar-based validation tools such as DTD, XML Schema (XSD), or RELAX NG—which primarily define the structure, sequence, and data types of elements—Schematron focuses on finding patterns and enforcing business logic. Standardized under ISO/IEC 19757-3, it operates by evaluating assertions across the XML document tree to verify that specific data dependencies and semantic constraints are met.

The Role of XPath in Schematron

Schematron relies entirely on XML Path Language (XPath) to navigate XML nodes and evaluate rules. Because XPath allows navigation across any axis (parent, child, sibling, or ancestor), Schematron can evaluate relationships between non-adjacent elements—a task that is difficult or impossible with standard XSD.

Schematron uses XPath in two primary ways:

  1. Defining Context: Identifying target nodes to be tested.
  2. Evaluating Assertions: Running boolean expressions against those nodes to check for validity.

Core Components of a Schematron Document

A standard Schematron file is itself an XML document using elements from the http://purl.oclc.org/dsdl/schematron namespace. It consists of four main structural layers:

Example Structure

<schema xmlns="http://purl.oclc.org/dsdl/schematron">
  <pattern name="Order Validation">
    <rule context="Order">
      <assert test="TotalAmount = sum(LineItem/Price)">
        The TotalAmount must match the sum of all LineItem prices.
      </assert>
      <report test="ShippingDate and not(PaymentReceived)">
        An order cannot have a ShippingDate before PaymentReceived is recorded.
      </report>
    </rule>
  </pattern>
</schema>

Key Capabilities of Rule-Based Validation

Using XPath within Schematron unlocks capabilities beyond basic structural validation:

By combining the structural simplicity of XML with the expressive query power of XPath, Schematron serves as a flexible, complementary validation layer that ensures XML data satisfies complex domain requirements.