使用XmlDocument可向XML添加节点:先Load加载文件,再CreateElement创建节点并设置文本,通过AppendChild添加到指定父节点,最后Save保存修改,需注意路径与异常处理。

在C#中向XML文件添加新节点,通常使用 XmlDocument 类来加载、修改和保存XML内容。下面是一个简单实用的步骤说明,帮助你向XML文件中添加新节点。
1. 加载XML文件
使用 XmlDocument.Load() 方法读取现有XML文件。
var doc = new XmlDocument();doc.Load("example.xml"); // 替换为你的文件路径
2. 创建新节点
使用 CreateElement 创建元素节点,CreateTextNode 创建文本内容。
var newNode = doc.CreateElement("Book");var titleNode = doc.CreateElement("Title");
titleNode.InnerText = "C#编程指南";
newNode.AppendChild(titleNode);
你可以继续添加更多子节点,如作者、价格等:
var authorNode = doc.CreateElement("Author");authorNode.InnerText = "张三";
newNode.AppendChild(authorNode);
3. 添加到指定父节点
找到要添加新节点的父节点,比如根节点或某个已有分组。
var parentNode = doc.DocumentElement; // 获取根节点parentNode.AppendChild(newNode); // 将新节点加入
如果你想添加到某个特定子节点下,可以使用 SelectSingleNode 查找:
if (targetParent != null)
targetParent.AppendChild(newNode);
4. 保存修改
调用 Save() 方法将更改写回文件。
doc.Save("example.xml");完整示例结构如下:
var doc = new XmlDocument();doc.Load("example.xml");
var book = doc.CreateElement("Book");
var title = doc.CreateElement("Title");
title.InnerText = "深入理解C#";
book.AppendChild(title);
var author = doc.CreateElement("Author");
author.InnerText = "李四";
book.AppendChild(author);
doc.DocumentElement.AppendChild(book);
doc.Save("example.xml");
对应的XML结构示例(example.xml):
执行后会新增一个 Book 节点。
基本上就这些,操作清晰且容易扩展。注意处理文件路径和异常(如文件不存在),可配合 try-catch 使用更安全。










