XML - Schematron Rule-Based XML Validation

Introduction

Schematron is a rule-based XML validation language designed to validate XML documents using logical assertions and business rules. Unlike XML Schema (XSD) and DTD, which primarily validate the structure, data types, and relationships between elements, Schematron focuses on validating the meaning and correctness of the data according to specific business requirements.

Schematron is standardized by ISO and uses XPath expressions to define validation rules. It is particularly useful in industries such as healthcare, finance, publishing, government, and manufacturing, where XML documents must satisfy complex business policies that cannot be expressed using XSD alone.

For example, XML Schema can verify that an employee ID exists and that the salary is a decimal value, but it cannot easily verify that the salary should be greater than zero only if the employee is active. Schematron can perform such logical checks efficiently.


Why Schematron is Needed

Traditional XML validation languages have limitations.

DTD validates:

  • Element hierarchy

  • Attributes

  • Required elements

XML Schema (XSD) validates:

  • Data types

  • Element order

  • Cardinality

  • Constraints such as minimum and maximum values

However, many real-world business rules involve relationships between multiple elements, conditional validations, and context-sensitive checks.

For example:

  • An order marked as "Delivered" must have a delivery date.

  • A student with attendance below 75% cannot appear for examinations.

  • A patient's discharge date cannot be earlier than the admission date.

  • An invoice total should equal the sum of all item prices.

Such rules are difficult or impossible to define using XSD alone.

Schematron solves this problem.


Features of Schematron

Schematron provides several advanced capabilities.

Rule-Based Validation

Validation is performed through logical rules instead of structural definitions.

Example:

"If payment mode is Credit Card, then card number must be present."


XPath Support

Schematron uses XPath expressions to navigate XML documents.

This allows checking:

  • Parent-child relationships

  • Sibling elements

  • Attribute values

  • Mathematical conditions

  • Text content


Business Rule Validation

Schematron can validate organization-specific rules.

Example:

Every employee older than 60 years should have retirement status set to "Eligible."


Custom Error Messages

Instead of generic validation errors, Schematron allows meaningful messages.

Example:

Incorrect message:

Element missing.

Better Schematron message:

Order with Status='Delivered' must include DeliveryDate.

This makes debugging much easier.


Conditional Validation

Rules can depend on conditions.

Example:

If Country is India

then

State must be present.

Otherwise

State is optional.


Structure of a Schematron Document

A Schematron document mainly consists of:

  • Schema

  • Pattern

  • Rule

  • Assert

  • Report

Example structure

<schema>
    <pattern>
        <rule context="Employee">
            <assert test="Salary > 0">
                Salary must be greater than zero.
            </assert>
        </rule>
    </pattern>
</schema>

Each component has a specific responsibility.


Schema Element

The schema element is the root of the Schematron document.

Example

<schema xmlns="http://purl.oclc.org/dsdl/schematron">

It contains all validation rules.


Pattern Element

Patterns organize related validation rules.

Example

<pattern id="EmployeeRules">

You may have separate patterns such as:

Employee Rules

Invoice Rules

Customer Rules

Medical Rules

This improves readability.


Rule Element

Each rule specifies where validation should occur.

Example

<rule context="Employee">

This means:

Apply validation to every Employee element.


Assert Element

Assert checks whether a condition is true.

Syntax

<assert test="condition">

Example

<assert test="Salary > 0">
Salary must be greater than zero.
</assert>

If the condition is false, validation fails.


Report Element

Report is opposite to Assert.

It generates a message only when a condition is true.

Example

<report test="Age > 60">
Employee is eligible for retirement.
</report>

This is useful for warnings rather than errors.


Example XML Document

<Employee>

<EmployeeID>1001</EmployeeID>

<Name>Rahul</Name>

<Age>30</Age>

<Salary>45000</Salary>

<Status>Active</Status>

</Employee>

Suppose the company policy states:

Salary must always be positive.

Schematron Rule

<rule context="Employee">

<assert test="Salary > 0">

Salary should be greater than zero.

</assert>

</rule>

Since salary is 45000, validation passes.


If salary becomes

<Salary>-1000</Salary>

Validation produces

Salary should be greater than zero.

Example of Conditional Validation

Suppose the XML is

<Employee>

<Status>Married</Status>

<SpouseName>Priya</SpouseName>

</Employee>

Business Rule

If employee is married,

SpouseName must exist.

Schematron Rule

<rule context="Employee">

<assert test="Status!='Married' or SpouseName">

Married employees must have spouse information.

</assert>

</rule>

Example of Date Validation

XML

<Project>

<StartDate>2025-01-01</StartDate>

<EndDate>2024-12-20</EndDate>

</Project>

Business Rule

End date cannot be before start date.

Schematron

<assert test="EndDate >= StartDate">

End date must be after start date.

</assert>

Example of Invoice Validation

XML

<Invoice>

<Total>1000</Total>

<Items>

<Item>

<Price>600</Price>

</Item>

<Item>

<Price>400</Price>

</Item>

</Items>

</Invoice>

Schematron Rule

<assert test="Total = sum(Items/Item/Price)">

Invoice total is incorrect.

</assert>

This verifies financial accuracy.


Example in Healthcare

Medical XML records often require strict validation.

Business Rules

  • Patient age cannot be negative.

  • Discharge date must be after admission date.

  • Blood group should follow approved values.

  • Prescription should contain at least one medicine.

Schematron validates these conditions effectively.


Example in Banking

Bank XML files may require:

  • Loan amount should be greater than zero.

  • Interest rate must be within policy limits.

  • Customer ID must exist.

  • Closed account cannot have active transactions.

Schematron easily handles these validations.


Example in E-Commerce

An online shopping system may require:

  • Delivered orders should have tracking numbers.

  • Cancelled orders should not have shipping dates.

  • Discount cannot exceed product price.

  • Quantity should always be greater than zero.

These business rules can be enforced using Schematron.


Advantages of Schematron

  • Validates complex business logic that XSD cannot express.

  • Uses XPath for flexible and precise rule definitions.

  • Supports meaningful and customizable error messages.

  • Organizes validation rules into reusable patterns.

  • Can work alongside DTD and XML Schema for comprehensive validation.

  • Eases maintenance by separating business rules from structural definitions.

  • Suitable for validating documents in healthcare, finance, publishing, and government sectors.

  • Helps ensure data consistency across XML-based applications.


Limitations of Schematron

  • Does not define XML document structure like XSD or DTD.

  • Requires XPath knowledge to create effective validation rules.

  • Validation can become slower with very large XML documents containing numerous complex rules.

  • Rules may become difficult to manage if not organized properly.

  • Often used in combination with XML Schema rather than as a complete replacement.


Best Practices

  • Use XML Schema (XSD) to validate document structure and data types before applying Schematron rules.

  • Group related validation rules into separate patterns for better organization.

  • Write clear and descriptive error messages to simplify troubleshooting.

  • Avoid duplicating validation logic across multiple rules.

  • Thoroughly test Schematron rules with both valid and invalid XML documents.

  • Keep XPath expressions as simple and efficient as possible to improve performance.

  • Document business rules clearly so that future maintenance is easier.


Conclusion

Schematron is a powerful XML validation language that complements DTD and XML Schema by validating business logic rather than just document structure. By leveraging XPath-based assertions, it can enforce complex conditions, cross-element relationships, and organizational policies that traditional schema languages cannot express. This makes Schematron an essential tool for applications where XML data must comply with strict business requirements, such as healthcare records, financial transactions, government documents, enterprise workflows, and e-commerce systems. When used alongside XML Schema, Schematron provides a complete and reliable validation framework for ensuring both structural correctness and business-rule compliance.