Search code examples
c#xmlschematron

Schematron.net structured error reporting


I am using the Schematron.net nuget package and I want to know if it's possible to get the output of a call to Validate to give the results in a structured format that I can then process. My existing solution relies on a try catch block and the assertion failures are all returned as the message within the exception as the error message. Is there a way to get this information as XML? I have seen this post which asks a similar question, but the answers don't refer to the Schematron.net implementation.

My code looks like this:

try
{
   var bookValidator = new Validator();
   bookValidator.AddSchema("book.xsd");
   bookValidator.Validate("book.xml");
}
catch (Exception ex)
{
   Console.WriteLine(ex.Message);
}

Solution

  • It's pretty simple actually. I just realised that passing a suitable enumeration of OutputFormatting to the Validator constructor allows me to control the format of the message in the exception, like so:

    try
    {
       //OutputFormatting is a public enum from the Schematron library. Valid values include boolean, default, Log, simple and XML.
       OutputFormatting format = OutputFormatting.XML;
       var bookValidator = new Validator(format);
       bookValidator.AddSchema("book.xsd");
       bookValidator.Validate("book.xml");
    }
    catch (Exception ex)
    {
       //ex.Message will now be in XML format and can be processed however I want!
       Console.WriteLine(ex.Message);
    }
    

    And there's your structured results. I hope that helps someone as it wasn't obvious to me.