使用XmlDocument或XDocument可修改XML节点值:1. XmlDocument通过Load加载文件,SelectSingleNode查找节点,修改InnerText并Save保存;2. XDocument用XDocument.Load加载,Descendants查找节点,设置Value后Save。需注意路径正确、节点存在及属性修改方式。

在 C# 中修改 XML 文件中的节点值,通常使用 XmlDocument 或 XDocument 类。下面介绍两种常用方法,你可以根据需要选择。
步骤如下:
示例代码:
using System.Xml;
<p>XmlDocument doc = new XmlDocument();
doc.Load("example.xml"); // 加载文件</p><p>// 假设要修改 <person><name> 的值
XmlNode node = doc.SelectSingleNode("//person/name");
if (node != null)
{
node.InnerText = "新名字";
}</p><p>doc.Save("example.xml"); // 保存修改
步骤类似:
示例代码:
using System.Xml.Linq;
<p>XDocument doc = XDocument.Load("example.xml");</p><p>var element = doc.Descendants("name").FirstOrDefault();
if (element != null)
{
element.Value = "新名字";
}</p><p>doc.Save("example.xml");
基本上就这些。选哪种方式取决于你的开发环境和习惯。XmlDocument 更稳定,XDocument 更简洁。
以上就是C# 怎么修改xml文件中的节点值的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号