System.Xml.XmlDocument 是 .NET Framework 中實現 W3C DOM (Document Object Model) Level 1/2 標準的類別,提供將 XML 文檔載入記憶體、建立樹狀結構、導航節點、查詢 (XPath)、修改、儲存等完整功能。適用於中小型 XML 文檔的隨機存取操作。
Load()、LoadXml()、Save()DocumentElement、SelectSingleNode()、SelectNodes() (XPath)CreateElement()、CreateAttribute()、AppendChild()、RemoveChild()XmlNode ↔ XmlElement、XmlAttributeusing System.Xml;
using System.Windows.Forms;
public static string GetAppSetting(string key)
{
var doc = new XmlDocument();
string configPath = Application.StartupPath + "/user.config";
if (!File.Exists(configPath)) return string.Empty;
doc.Load(configPath);
// XPath: 找到 configuration 下的 add 節點,key 屬性匹配
var node = doc.SelectSingleNode($"//configuration//add[@key='{key}']");
return node?.Attributes["value"]?.Value ?? string.Empty;
}
XmlReader/XmlWriter 流式處理,避免記憶體壓力。XmlNamespaceManager 註冊前綴。Load 會自動偵測 XML 宣告中的 encoding,儲存時預設 UTF-8。.NET Core / .NET 5+ 推薦使用 System.Xml.Linq.XDocument (LINQ to XML),語法更簡潔、支援 LINQ 查詢、效能更佳。