首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# XmlDocument 類別核心功能與實用範例

     編輯:程式設計綜合問答

XmlDocument 簡介

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、XmlAttribute

實用範例:讀取 App.config 設定值

using 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;
}

注意事項

  • 效能:大型 XML (>10MB) 建議使用 XmlReader/XmlWriter 流式處理,避免記憶體壓力。
  • 命名空間:查詢帶命名空間的 XML 時需使用 XmlNamespaceManager 註冊前綴。
  • 編碼:Load 會自動偵測 XML 宣告中的 encoding,儲存時預設 UTF-8。

現代替代方案

.NET Core / .NET 5+ 推薦使用 System.Xml.Linq.XDocument (LINQ to XML),語法更簡潔、支援 LINQ 查詢、效能更佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved