Home > Backend Development > C++ > How Can I Parse XML with Embedded Schema Validation in C#?

How Can I Parse XML with Embedded Schema Validation in C#?

Susan Sarandon
Release: 2025-01-21 18:52:15
Original
306 people have browsed it

How Can I Parse XML with Embedded Schema Validation in C#?

XML parsing and inline schema validation in C#

XML documents can reference external schemas using the xsi:schemaLocation attribute. However, when doing XML validation in C#, you may want to leverage the schema specified in the XML file rather than manually loading it.

In order to implement automatic verification based on inline mode, you can use the following methods:

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

public class ValidXSD
{
    public static void Main()
    {
        // 初始化 XmlReaderSettings 实例。
        XmlReaderSettings settings = new XmlReaderSettings
        {
            ValidationType = ValidationType.Schema,
            ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
                                XmlSchemaValidationFlags.ProcessSchemaLocation |
                                XmlSchemaValidationFlags.ReportValidationWarnings
        };

        // 注册验证事件处理程序。
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // 使用设置创建 XmlReader。
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // 处理 XML 文件。
        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

This method uses the ValidationType attribute to specify schema validation, and the associated ValidationFlags to indicate the use of inline schema and schema placement. ValidationEventHandler is used to handle any validation errors or warnings that may occur during parsing.

The above is the detailed content of How Can I Parse XML with Embedded Schema Validation 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