读取xml文件的方法 C#
时间: 2023-09-12 22:02:52 浏览: 100
在 C# 中读取 XML 文件有多种方法,以下是其中一种常用的方法:
1. 引入 `System.Xml` 命名空间。
2. 创建 `XmlDocument` 对象,加载要读取的 XML 文件。
```csharp
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("example.xml");
```
3. 获取 XML 文件中的节点和属性。
```csharp
XmlNodeList nodeList = xmlDoc.SelectNodes("//节点名称");
foreach (XmlNode node in nodeList)
{
string attributeValue = node.Attributes["属性名称"].Value;
string nodeValue = node.InnerText;
}
```
其中,`//节点名称` 表示获取所有名称为 "节点名称" 的节点,`node.Attributes["属性名称"].Value` 表示获取该节点的名为 "属性名称" 的属性值,`node.InnerText` 表示获取该节点的文本内容。
完整代码示例:
```csharp
using System.Xml;
public class XmlReader
{
public static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("example.xml");
XmlNodeList nodeList = xmlDoc.SelectNodes("//节点名称");
foreach (XmlNode node in nodeList)
{
string attributeValue = node.Attributes["属性名称"].Value;
string nodeValue = node.InnerText;
Console.WriteLine("属性值:" + attributeValue);
Console.WriteLine("节点值:" + nodeValue);
}
}
}
```
阅读全文
相关推荐















