Search code examples
c#xmlschematron

Fail to validate XML with Schematron.NET


I am using Schematron.NET in a C# project to validate the XML (format below):

<bpr:item xmlns:bpr="http://etcetc.com">
<bpr:name>Title</bpr:name>
<bpr:contents>
<process>Process1</process>
</bpr:contents>
</bpr:item>

The sch file contains the following code:

<ns prefix="bpr" uri="http://etcetc.com"/>
<pattern name="Title" xmlns="http://purl.oclc.org/dsdl/schematron">
<rule context="item/contents">
<assert test="process='Process2'">Process not found.</assert>
</rule>
</pattern>

And this is the C# using NMatrix.Schematron.dll:

Validator val = new Validator();
XPathDocument docnav = new XPathDocument(xmlPath);
XPathNavigator nav = docnav.CreateNavigator();
nav.MoveToRoot();
val.AddSchema(schemaFilePath);
val.ValidateSchematron(nav);

Why is it not retrieving any results?


Solution

  • I can't speak to the C# code, but here are some things in the Schematron code:

    1. As mentioned in the comments, the Schematron code should have a single document element. In Schematron, it is the <schema> element.
    2. When you refer to elements in the "http://etcetc.com" namespace, you need to use the "bpr:" namespace prefix that you declared in the Schematron schema.
    3. The Schematron <pattern> element cannot have a @name attribute. It can have an @id attribute or a <title> child element (both are optional).

    Here's a working example of the Schematron code that generates a failed assert on the sample XML document you provided:

    <schema xmlns="http://purl.oclc.org/dsdl/schematron">
      <ns prefix="bpr" uri="http://etcetc.com"/>
      <pattern>
        <rule context="bpr:item/bpr:contents">
          <assert test="process='Process2'">Process not found.</assert>
        </rule>
      </pattern>
    </schema>