温馨提示×

c# xmlhelper 怎样进行XML验证

c#
小樊
94
2024-07-15 16:43:37
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

您可以使用C#中的XmlReader类来验证XML文档。以下是一个简单的示例代码来进行XML验证:

using System;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        string xmlFilePath = "path_to_your_xml_file.xml";

        try
        {
            // 创建XmlReaderSettings对象并设置ValidationType为Schema
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;

            // 添加XML Schema文件的路径
            settings.Schemas.Add(null, "path_to_your_xml_schema.xsd");

            // 添加验证事件处理程序
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            // 创建XmlReader对象并进行XML验证
            using (XmlReader reader = XmlReader.Create(xmlFilePath, settings))
            {
                while (reader.Read()) { }
            }

            Console.WriteLine("XML validation successful.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("XML validation failed: " + ex.Message);
        }
    }

    // 验证事件处理程序
    private static void ValidationCallBack(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.WriteLine("Warning: " + e.Message);
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

在上面的代码中,您需要将path_to_your_xml_file.xml替换为您要验证的XML文件路径,并将path_to_your_xml_schema.xsd替换为XML Schema文件的路径。然后,程序会读取XML文件并根据XML Schema对其进行验证。如果验证成功,则输出“XML validation successful”,否则输出错误消息。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c# xmlhelper 如何使用LINQ处理XML

0