C# 读XML文件的简单例子(c#中xml)
在C#中,可以使用XmlDocument类或XDocument类来读取XML文件。
这两个类都提供了用于解析和操作XML文档的方法和属性。
下面是使用XmlDocument类读取XML文件的示例:
using System;
using System.Xml;
class Program
{
static void Main()
{
// 创建一个XmlDocument实例
XmlDocument xmlDoc = new XmlDocument();
// 加载XML文件
xmlDoc.Load("example.xml");
// 获取根节点
XmlNode root = xmlDoc.DocumentElement;
// 遍历子节点
foreach (XmlNode node in root.ChildNodes)
{
// 获取节点的名称和值
string nodeName = node.Name;
string nodeValue = node.InnerText;
Console.WriteLine("节点名称: " + nodeName);
Console.WriteLine("节点值: " + nodeValue);
Console.WriteLine();
}
}
}
在上面的示例中,我们使用XmlDocument类创建一个XML文档对象,并使用Load方法加载名为"example.xml"的XML文件。然后,我们获取根节点,并使用ChildNodes属性遍历所有子节点。对于每个子节点,我们获取节点的名称和值,并将其打印到控制台。
另一种读取XML文件的方法是使用XDocument类。
下面是使用XDocument类读取XML文件的示例:
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// 加载XML文件
XDocument xmlDoc = XDocument.Load("example.xml");
// 获取根元素
XElement root = xmlDoc.Root;
// 遍历子元素
foreach (XElement element in root.Elements())
{
// 获取元素的名称和值
string elementName = element.Name.LocalName;
string elementValue = element.Value;
Console.WriteLine("元素名称: " + elementName);
Console.WriteLine("元素值: " + elementValue);
Console.WriteLine();
}
}
}
在上面的示例中,我们使用XDocument类加载名为"example.xml"的XML文件。然后,我们获取根元素,并使用Elements方法遍历所有子元素。对于每个子元素,我们获取元素的名称和值,并将其打印到控制台。
无论您选择使用XmlDocument类还是XDocument类,都可以根据需要读取和操作XML文件中的数据。