Home > Backend Development > C++ > How to Automatically Validate XML Against a Referenced XSD in C#?

How to Automatically Validate XML Against a Referenced XSD in C#?

Linda Hamilton
Release: 2025-01-21 19:06:09
Original
537 people have browsed it

How to Automatically Validate XML Against a Referenced XSD in C#?

Validating XML against referenced XSD in C#

When an XML file with a specified schema location is loaded, it is expected that the file will be automatically validated against the schema in C#. However, manually specifying the schema seems necessary.

In order to validate XML without manually specifying the schema, you must create an instance of XmlReaderSettings and pass it to XmlReader on creation. This allows you to subscribe to ValidationEventHandler in settings to receive validation errors.

Here is a modified code example to achieve this:

<code class="language-csharp">using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {
        // 初始化验证设置。
        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);

        // 使用指定的验证设置加载 XML 文件。
        XmlDocument asset = new XmlDocument();
        XmlReader reader = XmlReader.Create("XML_file_path.xml", settings);

        // 解析文件。
        while (reader.Read()) ;
    }

    // 显示验证错误或警告。
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\t警告:未找到匹配的架构。未进行验证。" + args.Message);
        else
            Console.WriteLine("\t验证错误: " + args.Message);
    }
}</code>
Copy after login

Using XmlReaderSettings you can automatically validate XML files against referenced XSDs without explicitly specifying the schema.

The above is the detailed content of How to Automatically Validate XML Against a Referenced XSD in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template