C#操作XML最常用方式是XmlDocument类,基于DOM加载整个XML到内存,支持增删改查、遍历和保存,适合几MB以内中小型文件。

C# 操作 XML 文件最常用、最直接的方式就是用 XmlDocument 类,它基于 DOM(文档对象模型),把整个 XML 加载到内存中,支持增删改查、遍历和保存,适合中小型 XML 文件(几 MB 以内)。下面讲清楚怎么读、怎么写、怎么改,不绕弯子。
用 Load() 或 LoadXml() 把 XML 载入内存,再用 SelectNodes() / SelectSingleNode() 配合 XPath 查找节点。
doc.Load("config.xml");
doc.LoadXml("<root><item id="1">A</item></root>");
var nodes = doc.SelectNodes("//item");
string id = node.Attributes["id"]?.Value;
string text = node.InnerText.Trim();
用 CreateElement()、CreateAttribute() 等方法生成节点,再用 AppendChild() 或 InsertBefore() 插入到目标位置。
XmlElement newItem = doc.CreateElement("item");
newItem.SetAttribute("id", "3");
newItem.InnerText = "New Value";
doc.DocumentElement?.AppendChild(newItem);
找到目标节点后,直接改 InnerText、Attributes,或调用 RemoveChild() / RemoveAll()。
node.InnerText = "Updated";
node.Attributes["id"].Value = "99";
parentNode.RemoveChild(targetNode);
node.RemoveAll();
改完别忘了保存。用 Save() 写入文件,用 OuterXml 获取字符串形式(含根节点),InnerXml 只取内部内容。
doc.Save("config.xml");
string xmlStr = doc.OuterXml;
doc.PreserveWhitespace = false;,再用 XmlTextWriter 或 .NET 6+ 的 XmlWriter.Create(..., new XmlWriterSettings { Indent = true })
基本上就这些。注意:操作前建议加异常处理(比如文件不存在、XML 格式错误),多层嵌套时 XPath 写准一点,避免空引用。小项目够用,大文件建议换 XmlReader/XmlWriter 流式处理。
以上就是C#怎么操作XML文件 C# XmlDocument读写XML方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号