c#读取XML文档的操作
在 C# 中,可以使用 XmlDocument
类或 XDocument
类来读取 XML 文档。下面是使用这两种方法的示例:
1.使用 XmlDocument
类:
using System;
using System.Xml;
class Program
{
static void Main()
{
// 创建一个新的 XmlDocument 对象
XmlDocument xmlDoc = new XmlDocument();
// 加载 XML 文档
xmlDoc.Load("path/to/your/xml/file.xml");
// 选择根节点
XmlNode root = xmlDoc.DocumentElement;
// 遍历子节点
foreach (XmlNode node in root.ChildNodes)
{
Console.WriteLine($"Node Name: {node.Name}, Node Value: {node.InnerText}");
}
}
}
2.使用 XDocument
类(需要引入 System.Xml.Linq
命名空间):
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// 加载 XML 文档
XDocument xDoc = XDocument.Load("path/to/your/xml/file.xml");
// 选择根元素
XElement root = xDoc.Root;
// 遍历子元素
foreach (XElement element in root.Elements())
{
Console.WriteLine($"Element Name: {element.Name}, Element Value: {element.Value}");
}
}
}