문제

I am trying to test Xsd Validation using Saxon. When I get to the actual validation, only the first error is caught because validator.Run() throws an exception when it gets to the first error, and does not continue afterwards. This is obviously not what you want when you have an xml file with many errors. Is there a way to continue validation after the exception is thrown or is there another method of validation using Saxon?

This code is based off the one example for validation that Saxon has in it's samples folder of documentation and this is the section that runs the validation.

SchemaValidator validator = manager.NewSchemaValidator();
using (Stream xmlFile = File.OpenRead(fileName))
{
    using (XmlReader xmlValidatingReader = XmlReader.Create(xmlFile))
    {
        validator.SetSource(xmlValidatingReader);
        validator.ErrorList = new ArrayList();
        try
        {
            validator.Run();
        }
        catch (Exception)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Instance validation failed with " + validator.ErrorList.Count + " errors");
            foreach (StaticError error in validator.ErrorList)
            {
                sb.AppendLine("At line " + error.LineNumber + ": " + error.Message);
                tbXsdOutput.Text = sb.ToString();
            }
            return;
        }
    }
}
도움이 되었습니까?

해결책

Here's how I configured Saxonica to return more than one error:

proc.SetProperty(net.sf.saxon.lib.FeatureKeys.VALIDATION_WARNINGS,"true");

Working code below:

static void Main(string[] args)
{
    try
    {
        errors = new ArrayList();
        Saxon.Api.Processor proc = new Processor(true);
        proc.SetProperty(net.sf.saxon.lib.FeatureKeys.VALIDATION_WARNINGS,"true");
        //this is the property to set!

        SchemaManager schemaManager = proc.SchemaManager;

        FileStream xsdFs = new FileStream(@"C:\path\to.xsd", FileMode.Open);

        schemaManager.Compile(XmlReader.Create(xsdFs));
        SchemaValidator schemaValidator = schemaManager.NewSchemaValidator();

        FileStream xmlFs = new FileStream(@"C:\path\to.xml", FileMode.Open);

        schemaValidator.SetSource(XmlReader.Create(xmlFs));
        schemaValidator.ErrorList = errors;
        schemaValidator.Run();
    }
    catch(net.sf.saxon.type.ValidationException e)
    {
        foreach(StaticError error in errors)
        {
            Console.WriteLine(error.ToString());
        }
        Console.ReadKey(true);
        Environment.Exit(0);

    }

    foreach (StaticError error in errors)
    {
        Console.WriteLine(error.ToString());
    }
    Console.ReadKey(true);
}

You can see more about the VALIDATION_WARNINGS option here.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top