c# xml文件的读写
时间: 2023-12-05 22:05:49 浏览: 107
以下是C#中读写XML文件的示例代码:
1. 读取XML文件
```csharp
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument(); doc.Load("file.xml"); // 加载XML文件
XmlNodeList nodes = doc.SelectNodes("//book"); // 选择所有book节点
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.Attributes["name"].Value); // 输出name属性的值
}
}
}
```
2. 写入XML文件
```csharp
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("books"); // 创建根节点
doc.AppendChild(root);
XmlElement book1 = doc.CreateElement("book"); // 创建book节点
book1.SetAttribute("name", "book1"); // 设置name属性
root.AppendChild(book1);
XmlElement book2 = doc.CreateElement("book");
book2.SetAttribute("name", "book2");
root.AppendChild(book2);
doc.Save("file.xml"); // 保存XML文件
}
}
```
阅读全文
相关推荐
















