使用 XSD 文件进行 XML 验证

问题描述

我尝试使用 xml 架构验证我的 xml 结构。

此处给出了此代码示例:https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.validate?view=net-5.0

 XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add("http://www.contoso.com/books","contosoBooks.xsd");
        settings.ValidationType = ValidationType.Schema;

        XmlReader reader = XmlReader.Create("contosoBooks.xml",settings);
        XmlDocument document = new XmlDocument();
        document.Load(reader);

        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

        // the following call to Validate succeeds.
        document.Validate(eventHandler);

        // add a node so that the document is no longer valid
        XPathNavigator navigator = document.CreateNavigator();
        navigator.MovetoFollowing("price","http://www.contoso.com/books");
        XmlWriter writer = navigator.InsertAfter();
        writer.WriteStartElement("anotherNode","http://www.contoso.com/books");
        writer.WriteEndElement();
        writer.Close();

        // the document will Now fail to successfully validate
        document.Validate(eventHandler);

问题是,当我使用非有效 xml 文档时,我已经在线上出现了 System.Xml.Schema.XmlSchemaValidationException 类型的异常:

XmlReader reader = XmlReader.Create("contosoBooks.xml",settings);

这是否意味着您不再需要在 C# 6 中使用这个 Validate(eventHandler) 方法?或者它会处理一些特定的验证问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)