C#读写XML
时间: 2023-06-21 19:15:11 浏览: 131
C#中读写XML文件可以使用System.Xml命名空间下的XmlDocument类和XmlTextWriter类。
读取XML文件:
```csharp
using System.Xml;
// 创建XmlDocument对象
XmlDocument doc = new XmlDocument();
// 加载XML文件
doc.Load("文件路径");
// 获取根节点
XmlNode root = doc.SelectSingleNode("根节点名称");
// 获取子节点列表
XmlNodeList nodeList = root.ChildNodes;
foreach(XmlNode node in nodeList)
{
// 获取节点的属性值
string attrValue = node.Attributes["属性名称"].Value;
// 获取节点的文本值
string textValue = node.InnerText;
// TODO: 处理节点数据
}
```
写入XML文件:
```csharp
using System.Xml;
// 创建XmlDocument对象
XmlDocument doc = new XmlDocument();
// 创建根节点
XmlElement root = doc.CreateElement("根节点名称");
doc.AppendChild(root);
// 创建子节点
XmlElement child = doc.CreateElement("子节点名称");
// 设置子节点的属性值
child.SetAttribute("属性名称", "属性值");
// 设置子节点的文本值
child.InnerText = "文本值";
root.AppendChild(child);
// 创建XmlTextWriter对象
XmlTextWriter writer = new XmlTextWriter("文件路径", null);
// 设置缩进
writer.Formatting = Formatting.Indented;
// 保存XML文件
doc.WriteTo(writer);
writer.Close();
```
注意事项:
- 读取XML文件时,需要先加载XML文件;
- 写入XML文件时,需要先创建XML节点和XML属性,并将它们添加到XML文档中,最后使用XmlTextWriter类将XML文档写入到磁盘文件中。
阅读全文
相关推荐
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)