您可以使用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”,否則輸出錯誤消息。