Skip to content
Philip Helger edited this page Nov 16, 2026 · 2 revisions

This page explains how to validate XML documents with ph-schematron from Java code. It assumes basic knowledge of XML, XPath, XSLT and Schematron. See Home for the available modules and engines, and XSLT processors for the choice between Saxon and phoxtrot.

Validity check and SVRL

Schematron provides validation mechanisms for XML documents that go beyond DTD and XML Schema. DTD and XML Schema test the structure and the data types of the content of an XML document, whereas Schematron can check relations between the parts of an XML document.

ph-schematron offers two kinds of validation:

  • A validity check, that only tells whether the XML document conforms to the Schematron rules or not.
  • The creation of an SVRL ("Schematron Validation Report Language") document. It is an XML document that lists exactly which assertions failed and which reports succeeded.

Common API

All engines implement the interface com.helger.schematron.ISchematronResource. A resource is created with the builder of the respective engine class, e.g. SchematronResourceSCH.builderFromFile (aFile).build (). Builders exist for files, class path resources, URLs, input streams, byte arrays and strings (builderFromFile, builderFromClassPath, builderFromURL, builderFromInputStream, builderFromByteArray, builderFromString), and with builder (IReadableResource) for any other resource.

The interface offers the following methods:

  • boolean isValidSchematron () checks whether the Schematron itself is valid and can be used for validation.
  • EValidity getSchematronValidity (...) is the validity check: it returns EValidity.VALID or EValidity.INVALID, but not the reason. The pure XPath engine stops at the first failed assert or successful report. The XSLT based engines create the full SVRL and evaluate it afterwards, so this method is not faster than creating the SVRL.
  • Document applySchematronValidation (...) returns the SVRL as a DOM document.
  • SchematronOutputType applySchematronValidationToSVRL (...) returns the SVRL as a JAXB object, which makes it easier to access its content.

Each of the methods accepts the XML to validate as an IHasInputStream (e.g. a FileSystemResource), a javax.xml.transform.Source or a DOM Node with an optional base URI.

The class com.helger.schematron.svrl.SVRLMarshaller reads and writes SVRL documents and converts between the DOM and the JAXB representation. By default it validates the SVRL against the SVRL XML Schema contained in the library.

To get the failed asserts and successful reports from a SchematronOutputType, use SVRLHelper.getAllFailedAssertionsAndSuccessfulReports (SchematronOutputType). It returns a list of AbstractSVRLMessage, the common base class of SVRLFailedAssert and SVRLSuccessfulReport. Note that by default both failed asserts and successful reports make a document invalid.

Validation via XSLT

The classic way to perform a Schematron validation is to convert the Schematron into an XSLT stylesheet, and to apply this stylesheet to the XML documents to validate. The output of this transformation is an SVRL document. The engines ISO Schematron (SchematronResourceSCH), SchXslt (SchematronResourceSchXslt_XSLT2), SchXslt2 (SchematronResourceSchXslt2) and Pure XSLT (SchematronResourcePureXslt) work this way.

The conversion from Schematron to XSLT is costly, especially for large rule sets. The created XSLT can be applied to any number of XML documents, so ph-schematron caches it: a resource compiles its Schematron once, and by default the compiled XSLT is shared between all resources of the same Schematron. Note that the created XSLT depends on the selected Schematron phase and on the parameters of the conversion.

To avoid the conversion at runtime completely, the XSLT can be created at build time with the Maven plugin (goal convert), the ANT tasks or the Command line client. The prebuilt XSLT is then used with SchematronResourceXSLT from ph-schematron-xslt. A phase cannot be selected for a prebuilt XSLT, as the phase was already applied during the conversion.

A simple validity check of an XML file with a Schematron file looks like this:

public static boolean validateXMLViaXSLTSchematron (@NonNull final File aSchematronFile,
                                                    @NonNull final File aXMLFile) throws Exception
{
  final ISchematronResource aResSCH = SchematronResourceSCH.builderFromFile (aSchematronFile).build ();
  if (!aResSCH.isValidSchematron ())
    throw new IllegalArgumentException ("Invalid Schematron!");
  return aResSCH.getSchematronValidity (new StreamSource (aXMLFile)).isValid ();
}

The same example, but creating the SVRL:

public static SchematronOutputType validateXMLViaXSLTSchematronFull (@NonNull final File aSchematronFile,
                                                                     @NonNull final File aXMLFile) throws Exception
{
  final ISchematronResource aResSCH = SchematronResourceSCH.builderFromFile (aSchematronFile).build ();
  if (!aResSCH.isValidSchematron ())
    throw new IllegalArgumentException ("Invalid Schematron!");
  return aResSCH.applySchematronValidationToSVRL (new StreamSource (aXMLFile));
}

The builders of the XSLT based engines offer additional settings, e.g. phase (String), parameters (Map), xsltProcessor (ISchematronXsltProcessor) and outputValidityDeterminator (ISchematronOutputValidityDeterminator). The latter decides which SVRL elements make a document invalid; besides the default (failed asserts and successful reports) there are SchematronOutputValidityDeterminatorFailedAssertOnly and SchematronOutputValidityDeterminatorSuccessfulReportOnly.

Validation via Pure XPath

As an alternative to the XSLT based approach, ph-schematron-pure offers a Java implementation of the Schematron XPath binding: com.helger.schematron.pure.SchematronResourcePureXPath (its pre-v10 name SchematronResourcePure was removed in v11.0.0). It creates the same results as the XSLT approach - validity checks and SVRL documents - without the conversion to XSLT. Its limitation is that it only supports XPath expressions in the Schematron, but no XSLT (e.g. no xsl:function). For Schematrons with XSLT content, use one of the XSLT based engines.

Internally, a validation with the pure XPath engine performs the following steps:

  1. Read the Schematron (PSReader). All includes are resolved, so that one large Schematron is created.
  2. Determine the query binding (PSQueryBindingRegistry). If the Schematron specifies none, the XPath binding is used.
  3. Preprocess the Schematron (PSPreprocessor) to resolve abstract patterns, abstract rules and extends.
  4. Bind the preprocessed Schematron with the query binding. In this step the phase is selected and all XPath expressions are compiled.
  5. Validate the XML documents with the bound Schematron.

SchematronResourcePureXPath caches the bound Schematron, so that the steps 1 to 4 are performed only once per Schematron.

A simple validity check looks like this:

public static boolean validateXMLViaPureSchematron (@NonNull final File aSchematronFile,
                                                    @NonNull final File aXMLFile) throws Exception
{
  final ISchematronResource aResPure = SchematronResourcePureXPath.builderFromFile (aSchematronFile).build ();
  if (!aResPure.isValidSchematron ())
    throw new IllegalArgumentException ("Invalid Schematron!");
  return aResPure.getSchematronValidity (new StreamSource (aXMLFile)).isValid ();
}

The same steps can also be performed with the lower level API. Note that nothing is cached here, so the Schematron is read and compiled every time the method is called:

public static boolean validateXMLViaPureSchematron2 (@NonNull final File aSchematronFile,
                                                     @NonNull final File aXMLFile) throws Exception
{
  // Read the schematron from file
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  if (!aSchema.isValid (new DoNothingPSErrorHandler ()))
    throw new IllegalArgumentException ("Invalid Schematron!");
  // Resolve the query binding to use
  final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
  // Pre-process schema
  final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
  aPreprocessor.setKeepTitles (true);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  // Bind the pre-processed schema
  final IPSBoundSchema aBoundSchema = aQueryBinding.bind (aPreprocessedSchema);
  // Read the XML file
  final Document aXMLNode = DOMReader.readXMLDOM (aXMLFile);
  if (aXMLNode == null)
    return false;
  // Perform the validation
  return aBoundSchema.validatePartially (aXMLNode, FileHelper.getAsURLString (aXMLFile)).isValid ();
}

IPSBoundSchema offers validatePartially (validity check, stops at the first error), validateComplete (creates the SVRL) and validate with an own IPSValidationHandler.

The Schematron ISO standard defines a "minimal syntax" in which all includes, abstract patterns and abstract rules are resolved. The preprocessor is not called "minifier", because some minimisations would change the SVRL: if e.g. all report elements were converted to assert elements, the SVRL would contain failed-assert instead of successful-report elements. By default PSPreprocessor creates a minimal Schematron, but its setters allow to keep certain elements (e.g. setKeepTitles, setKeepDiagnostics, setKeepReports, setKeepEmptyPatterns).

Working with the Schematron model

ph-schematron-model contains the Java object model of a Schematron, with com.helger.schematron.model.PSSchema as root. Its hierarchy follows the XML structure of Schematron: a PSSchema contains PSPattern objects, which contain PSRule objects, and so on. PSReader reads a Schematron into the model, PSWriter writes it back, and getAsMicroElement () converts each model element into an XML structure.

The following example reads a Schematron file, sets a title and writes it back to the same file:

public static boolean readModifyAndWrite (@NonNull final File aSchematronFile) throws Exception
{
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  final PSTitle aTitle = new PSTitle ();
  aTitle.addText ("Created by ph-schematron");
  aSchema.setTitle (aTitle);
  return MicroWriter.writeToFile (aSchema.getAsMicroElement (), aSchematronFile).isSuccess ();
}

Own query bindings

The pure XPath engine allows to add own query bindings. A query binding implements com.helger.schematron.pure.binding.IPSQueryBinding (and usually its own com.helger.schematron.pure.bound.IPSBoundSchema) and is registered with PSQueryBindingRegistry.registerQueryBinding (String, IPSQueryBinding). An existing query binding cannot be replaced.

The predefined XPath query binding is registered for the names xpath, xpath2, xpath3, xslt, xslt2 and xslt3, and is used when the Schematron has no queryBinding attribute. The xslt* names are mapped to the XPath binding as well, so that Schematrons declaring them can be validated as long as they only use XPath; XSLT elements such as xsl:function are still not supported.

Examples in the source code

The examples on this page are taken from the classes DocumentationExamples in the tests of ph-schematron-xslt and ph-schematron-pure-xpath.

Clone this wiki locally