I have two XML files, good and bad. I need to validate these with an XML Schematron file. The Schematron file I am asked to validate is an XML with SCH tags. I was able to convert this XML file to an XSL file with the help of Oxygen XML, but I think there are different XSLS called iso XSL and SVRL XSL.
How should I go about it?
The validation method:
public static ValidationResult SchematronValidateXml(List<XmlDocument> xmlList)
{
var result = new ValidationResult();
foreach (var document in xmlList)
{
XmlTextReader reader = new XmlTextReader(new StringReader(document.OuterXml));
var resultStream = XslTransformer.Transform(reader);
using (var xmlReader = XmlReader.Create(resultStream))
{
bool hasError = xmlReader.ReadToFollowing("svrl:text");
while (hasError)
{
string id = "";
var elementId = (XmlElement)document.GetElementsByTagName("cbc:ID")[0];
if (elementId != null)
id = elementId.InnerText;
result.ErrorMessageList.Add("Schematron (" + id + ") :" + xmlReader.ReadElementContentAsString());
hasError = xmlReader.ReadToFollowing("svrl:text");
}
}
}
result.IsValid = !result.ErrorMessageList.Any();
return result;
}
The transformer method:
public static Stream Transform(XmlTextReader xmlTextReader)
{
try
{
var processor = new Processor();
var input = processor.NewDocumentBuilder().Build(xmlTextReader);
var compiler = processor.NewXsltCompiler();
var xslTextReader = new XmlTextReader(@"C:\Tools\Schematron\Schematron.xsl");
var transformer = compiler.Compile(xslTextReader).Load();
transformer.InitialContextNode = input;
var resultStream = new MemoryStream();
var serializer = processor.NewSerializer(resultStream);
transformer.Run(serializer);
resultStream.Position = 0;
return resultStream;
}
catch (Exception ex)
{
throw;
}
}