您可以使用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”,否则输出错误消息。