System.Xml.XmlDocument 是 .NET 傳統 DOM 模式 XML 操作類別,適合載入整份文件進行查詢、修改、儲存。本文整理常用操作模式與程式碼片段,方便快速參考。
using System.Xml;
XmlDocument xml = new XmlDocument();
// 從檔案載入
xml.Load(Server.MapPath("~/App_Data/bookstore.xml"));
// 從字串載入
xml.LoadXml("<root><item id='1'>Test</item></root>");
| 操作 | 程式碼 |
|---|---|
| 取得根節點 | XmlNode root = xml.DocumentElement; 或 xml.SelectSingleNode("/root") |
| 取得所有直接子節點 | XmlNodeList children = root.ChildNodes; |
| 判斷是否有子節點 | bool has = root.HasChildNodes; |
| XPath 查詢多個同名節點 | XmlNodeList list = xml.SelectNodes("/root/items/item"); |
| XPath 查詢單一節點 | XmlNode node = xml.SelectSingleNode("/root/items/item[@id='1']"); |
// 建立元素節點
XmlElement newItem = xml.CreateElement("item");
// 設定屬性
newItem.SetAttribute("id", "2");
// 設定內文
newItem.InnerText = "New Content";
// 或建立子元素
XmlElement sub = xml.CreateElement("detail");
sub.InnerText = "Detail text";
newItem.AppendChild(sub);
// 加入到父節點
root.AppendChild(newItem);
// 或插入到特定節點之前
root.InsertBefore(newItem, root.ChildNodes[1]);
// 修改屬性
node.Attributes["id"].Value = "99";
// 修改內文
node.InnerText = "Updated";
// 修改整段 XML (含子節點)
node.InnerXml = "<sub>New</sub>";
// 刪除屬性
node.Attributes.RemoveNamedItem("id");
// 刪除節點
root.RemoveChild(node);
string path = Server.MapPath("~/App_Data/bookstore.xml");
xml.Save(path);
// 或
xml.Save(HttpContext.Current.Server.MapPath("~/App_Data/bookstore.xml"));
public void AddBook(string title, string author, decimal price)
{
XmlDocument doc = new XmlDocument();
string path = Server.MapPath("~/App_Data/books.xml");
doc.Load(path);
XmlElement book = doc.CreateElement("book");
book.SetAttribute("isbn", Guid.NewGuid().ToString("N").Substring(0, 13));
XmlElement titleEl = doc.CreateElement("title");
titleEl.InnerText = title;
book.AppendChild(titleEl);
XmlElement authorEl = doc.CreateElement("author");
authorEl.InnerText = author;
book.AppendChild(authorEl);
XmlElement priceEl = doc.CreateElement("price");
priceEl.InnerText = price.ToString("F2");
book.AppendChild(priceEl);
doc.DocumentElement.AppendChild(book);
doc.Save(path);
}
| 特性 | XmlDocument (DOM) | XDocument (LINQ to XML) |
|---|---|---|
| 命名空間 | System.Xml | System.Xml.Linq |
| 查詢語法 | XPath | LINQ / XPath |
| 建構 XML | 冗長 (CreateElement/AppendChild) | 函數式建構 (new XElement(...)) |
| 效能 (大文件) | 載入整樹記憶體 | 同樣載入整樹,但查詢更優雅 |
| 適用場景 | 舊專案維護、需 XPath 相容 | 新專案首選、現代語法 |
建議:新專案優先使用 XDocument,程式碼更簡潔、型別安全、支援 LINQ 查詢。