Validating XML with Schematron

这一生的挚爱 提交于 2019-12-01 10:45:24

I recommend that you instead use Rick Jelliffe's reference implementation of ISO Schematron using pure XSLT, preferably XSLT 2.0, with an established XSLT processor such as Michael Kay's Saxon.

It would be better to use Saxon-HE from Nuget as it supports much more than Schematron now a days on .NET>

I am using Schematron.NET - Downlaod the source and examples, compile it or just use the DLL in the examples.

I then completely cut out XSLT of the picture because I did not need it. But some things like choice and similar are missing, but most can be tested using XPath anyway. Because its a bit old it does not implement ALL the features :(

This is an expanded version to validate with Schematron

using NMatrix.Schematron;
...
Schema schematronSchema = new Schema();
schematronSchema.Load(new FileStream("C:/thefile.sch", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
vld.AddSchema(schematronSchema);

vld.Validate(new MemoryStream(Encoding.UTF8.GetBytes(XML_String)));

I load using a file stream so that the file does not get locked, an annoyance common with the build in XSLT engine for .NET

Then inside the ".sch" file its just simple, much neater in my opinion way to validate schema data.

<?xml version="1.0" encoding="utf-8" ?>
<schema xmlns="http://www.ascc.net/xml/schematron" title="Schema for Blah">
<pattern name="A descriptive name">
 <rule context="DataNodeOrElement">
   <assert test="Xpath, where Name is element and @name is attribute"> Error Message </assert>
 </rule>
</pattern>

For example.

<root>
 <version>1</version>
  <data>
   <name surname="rulez">ppumkin</name>
   <age>na</age>
   <title/>
  </data>
 </root>

<rule context="data">
   <assert test="name != ''"> No name specified </assert>
   <assert test="@surname != 'rulez'"> This is not the ppumkin I know!</assert>

   <assert test="number(age) < 110"> Not a number or not specified</assert>
   <assert test="number(age) > 18"> Your under age. Get 'outa!ahere!</assert>
</rule>

Remember, an error only occurs when the test fails. ie if you interested in blocking under 18, you need to test if they are over 18. Its a bit weird to get used to.

I have never used Schematron before and honestly, now a days I treat XML like Ebola and anything to do with it - but sometimes we have no choice.

The examples in the Schematron.NET show you how to mix XSLT1/XLST2 with Schematron too for extra control and decisions.

Some programs, like oXygen, support schematron validation, but they probably use something like that RI under the hood.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!