一尘不染

针对C#中引用的XSD验证XML

c#

我有一个具有指定架构位置的XML文件,例如:

xsi:schemaLocation="someurl ..\localSchemaPath.xsd"

我想在C#中验证。当我打开文件时,Visual
Studio会根据架构对其进行验证并完美列出错误。但是,以某种方式,如果没有指定要验证的架构,我似乎无法在C#中自动验证它,如下所示:

XmlDocument asset = new XmlDocument();

XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath");
XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler);

asset.Schemas.Add(schema);

asset.Load(filename);
asset.Validate(DocumentValidationHandler);

我是否应该能够自动使用XML文件中指定的模式进行验证?我想念什么?


阅读 477

收藏
2020-05-19

共1个答案

一尘不染

您需要创建一个XmlReaderSettings实例,并在创建它时将其传递给XmlReader。然后,您可以订阅ValidationEventHandler设置中的以接收验证错误。您的代码最终将如下所示:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {

        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // Parse the file. 
        while (reader.Read()) ;

    }
    // Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}
2020-05-19