如何针对本地XSD架构验证本地XML文档 - ValidationEventHandler

时间:2015-08-11 18:40:06

标签: c# xml xsd schema

我试图简单地验证由我的程序(output.xml)创建的XML文档,该文档针对本地存储的名为myConfig.config.xsd的XSD架构。首先,这将无法运行,因为我尝试创建的Validation事件处理程序返回错误“'System.Xml.Schema.ValidationEventHandler'是'类型'但是像'变量'一样使用”这是有道理的,但我参考的教程下面就是这样做的。此外,我引用的xsd文件是本地的,其他教程似乎引用了具有在线命名空间的XSD。对于我来说,我只是将“schema”作为命名空间;这个可以吗?

这是我的方法:

public void Validate()
    {
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("schema", "myConfig.config.xsd"); //!!Here is where I just put "schema" as the namespace
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);

            XmlReader reader = XmlReader.Create("output.xml", settings);
            XmlDocument document = new XmlDocument();
            document.Load(reader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler); 
            //^Here is the problem line that won't let me build this program

            document.Validate(eventHandler);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    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);
    }

我正在尝试使用本指南来帮助我这样做:https://msdn.microsoft.com/en-us/library/ms162371(v=vs.110).aspx

1 个答案:

答案 0 :(得分:1)

该示例实际上有一个名为ValidationEventHandler的方法。你没有。更改您的eventHandler作业以使用您的实际事件处理程序方法:

ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallback);

您还可以使用隐式转换:

ValidationEventHandler eventHandler = ValidationCallback;

或者完全省略局部变量:

document.Validate(ValidationCallback);