XML(可扩展标记语言)是一种常用的数据存储和交换格式。在.NET中,System.Xml命名空间提供了处理XML文档的类和方法。
using System.Xml;
using System.Xml.Schema;
public static bool ValidateXmlWithXsd(string xmlPath, string xsdPath)
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, xsdPath);
settings.ValidationType = ValidationType.Schema;
// 设置验证事件处理程序
settings.ValidationEventHandler += (sender, args) =>
{
throw new XmlSchemaValidationException($"验证错误: {args.Message}");
};
using (XmlReader reader = XmlReader.Create(xmlPath, settings))
{
while (reader.Read()) { } // 读取整个文档以触发验证
}
return true;
}
catch (XmlSchemaValidationException)
{
return false;
}
}
public static bool ValidateXmlWithDtd(string xmlPath)
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += (sender, args) =>
{
throw new XmlException($"DTD验证错误: {args.Message}");
};
using (XmlReader reader = XmlReader.Create(xmlPath, settings))
{
while (reader.Read()) { }
}
return true;
}
catch (XmlException)
{
return false;
}
}
using System.Xml;
public static void ReadXmlWithXmlDocument(string xmlPath)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
// 读取根节点
XmlNode root = doc.DocumentElement;
// 遍历子节点
foreach (XmlNode node in root.ChildNodes)
{
Console.WriteLine($"节点名: {node.Name}, 值: {node.InnerText}");
}
}
using System.Xml.Linq;
public static void ReadXmlWithXDocument(string xmlPath)
{
XDocument doc = XDocument.Load(xmlPath);
// 查询所有元素
var elements = from el in doc.Descendants()
select el;
foreach (XElement el in elements)
{
Console.WriteLine($"元素名: {el.Name}, 值: {el.Value}");
}
}
using System.Xml;
public static void ReadXmlWithXmlReader(string xmlPath)
{
using (XmlReader reader = XmlReader.Create(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine($"元素: {reader.Name}");
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
Console.WriteLine($"属性: {reader.Name}={reader.Value}");
}
}
}
}
}
}
没有搜到相关的文章