private static string ValidateXmlFile(string inputFile, string transformFile)
{
try
{
if (string.IsNullOrWhiteSpace(inputFile))
{
throw new FileNotFoundException("Filename is empty");
}
inputFile = Path.GetFullPath(inputFile);
if (!File.Exists(inputFile))
{
throw new FileNotFoundException($"File: {inputFile} not found");
}
transformFile = Path.GetFullPath(transformFile);
if (!File.Exists(transformFile))
{
throw new FileNotFoundException($"File: {transformFile} not found");
}
Processor processor = new Processor();
DocumentBuilder builder = processor.NewDocumentBuilder();
builder.BaseUri = new Uri(inputFile);
XdmNode inputNode;
using (var inputStream = File.OpenRead(inputFile))
{
inputNode = builder.Build(inputStream);
}
XsltCompiler compiler = processor.NewXsltCompiler();
XsltExecutable executable;
using (var xsltStream = File.OpenRead(transformFile))
{
executable = compiler.Compile(xsltStream);
if (compiler.GetErrorList().Count != 0)
throw new Exception("Exception loading xsl!");
}
XsltTransformer transformer = executable.Load();
transformer.InitialContextNode = inputNode;
Serializer serializer = processor.NewSerializer();
using (var stringWriter = new StringWriter())
{
serializer.SetOutputWriter(stringWriter);
transformer.Run(serializer);
string result = stringWriter.ToString();
return result;
}
}
catch (Exception e)
{
return e.Message;
}
}
Since validation result is XML, we can parse failed validations like:
IEnumerable<FailedAssert> failedAsserts = doc.Descendants(svrl + "failed-assert")
.Select(fa => new FailedAssert
{
Flag = fa.Attribute("flag")?.Value,
Id = fa.Attribute("id")?.Value,
Test = fa.Attribute("test")?.Value,
Location = fa.Attribute("location")?.Value,
Text = fa.Element(svrl + "text")?.Value
});
SVRL is an abbreviation for 'Schematron Validation Report Language.'
FailedAssert class looks like:
public class FailedAssert
{
public string Flag { get; set; }
public string Id { get; set; }
public string Test { get; set; }
public string Location { get; set; }
public string ExceptionMessage { get; set; }
public string Text { get; set; }
}
Example download from here. For this example I used file 01.03a-INVOICE_uncefact.xml which I downloaded from here where I manipulated with DateTimeField. Instead of a date I wrote "test", in order to trigger a failed assertion. I also downloaded XSL file EN16931-CII-validation.xsl from "Koordinierungsstelle für IT-Standards" (KoSIT) GitHub repository.