c# - 使用 XSD 架构验证 XML,而无需使用 C# 更改 XML

标签 c# validation xsd

我有一个 XML 文件,其中没有 XML 架构,并且我需要根据 XSD 架构验证 XML。我见过很多将 XSD 注入(inject)到 XML 中然后验证 XML 的示例。我不想更改 XML,是否可以根据架构验证 XML,而不更改 XML?

最佳答案

用 C# 编写几行代码很容易。

我创建了一个简单的命令行界面实用程序,它采用两个参数:XML、XSD 并进行验证。

您可以下载here .

主要代码如下:

            // 1- Read XML file content
            reader = new XmlTextReader(XMLPath);

            // 2- Read Schema file content
            StreamReader SR = new StreamReader(XSDPath);

            // 3- Create a new instance of XmlSchema object
            XmlSchema Schema = new XmlSchema();
            // 4- Set Schema object by calling XmlSchema.Read() method
            Schema = XmlSchema.Read(SR,
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler));

            // 5- Create a new instance of XmlReaderSettings object
            XmlReaderSettings ReaderSettings = new XmlReaderSettings();
            // 6- Set ValidationType for XmlReaderSettings object
            ReaderSettings.ValidationType = ValidationType.Schema;
            // 7- Add Schema to XmlReaderSettings Schemas collection
            ReaderSettings.Schemas.Add(Schema);

            // 8- Add your ValidationEventHandler address to
            // XmlReaderSettings ValidationEventHandler
            ReaderSettings.ValidationEventHandler +=
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler);

            // 9- Create a new instance of XmlReader object
            XmlReader objXmlReader = XmlReader.Create(reader, ReaderSettings);


            // 10- Read XML content in a loop
            while (objXmlReader.Read())
            { /*Empty loop*/}

关于c# - 使用 XSD 架构验证 XML,而无需使用 C# 更改 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780327/

相关文章:

c# - 通过调用另一个方法退出一个方法

javascript - 使用 jquery 基于语言的验证

java - 未执行方法参数上的自定义注释

c# - 使用 StringReader 与 XmlNodeReader 反序列化对象属性

xml - Soap xml 响应使用 xsd 文件进行验证

c# - Unity内存问题资源图片

c# - 如何确定 .NET 代码是否在 ASP.NET 进程中运行?

c# - Azure Offline Sync 是否处理关系表?

asp.net - 如何在ASP.NET MVC 3中的HttpPost操作中禁用验证?

c# - 如何使用 XmlSerializer 反序列化大型文档中的节点