本文用一個「很笨但很直觀」的方法,帶初學者一步步了解在 C# 中存取 XML 節點的過程。已知有一份 bookstore.xml:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
往 <bookstore> 中插入一個新的 <book> 節點:先載入文件、用 SelectSingleNode 找到 bookstore,建立 book 元素並設定屬性,再逐一建立 title、author、price 子節點附加進去,最後存回檔案:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("bookstore.xml");
XmlNode root = xmlDoc.SelectSingleNode("bookstore"); // 查找 <bookstore>
XmlElement xe1 = xmlDoc.CreateElement("book"); // 建立 <book> 節點
xe1.SetAttribute("genre", "李贊紅"); // 設定 genre 屬性
xe1.SetAttribute("ISBN", "2-3631-4"); // 設定 ISBN 屬性
XmlElement xesub1 = xmlDoc.CreateElement("title");
xesub1.InnerText = "CS從入門到精通"; // 設定文字節點
xe1.AppendChild(xesub1); // 加入 <book>
XmlElement xesub2 = xmlDoc.CreateElement("author");
xesub2.InnerText = "候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3 = xmlDoc.CreateElement("price");
xesub3.InnerText = "58.3";
xe1.AppendChild(xesub3);
root.AppendChild(xe1); // 加入 <bookstore>
xmlDoc.Save("bookstore.xml");
把 genre 屬性值為「李贊紅」的節點,其 genre 值改成「update李贊紅」,並把該節點下 <author> 的文字改成「亞勝」。做法是遍歷 bookstore 的所有子節點,比對屬性後修改:
XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode xn in nodeList) {
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("genre") == "李贊紅") {
xe.SetAttribute("genre", "update李贊紅"); // 修改屬性
XmlNodeList nls = xe.ChildNodes;
foreach (XmlNode xn1 in nls) {
XmlElement xe2 = (XmlElement)xn1;
if (xe2.Name == "author") {
xe2.InnerText = "亞勝"; // 修改文字
break;
}
}
break;
}
}
xmlDoc.Save("bookstore.xml");
刪除 genre 為「fantasy」節點的 genre 屬性,並刪除 genre 為「update李贊紅」的整個節點:
XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode xn in xnl) {
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("genre") == "fantasy") {
xe.RemoveAttribute("genre"); // 刪除 genre 屬性
} else if (xe.GetAttribute("genre") == "update李贊紅") {
xe.RemoveAll(); // 刪除該節點的全部內容
}
}
xmlDoc.Save("bookstore.xml");
最後,用巢狀迴圈遍歷 bookstore 及其子節點,把屬性值與子節點文字印出來:
XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl) {
XmlElement xe = (XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre")); // 顯示屬性值
Console.WriteLine(xe.GetAttribute("ISBN"));
XmlNodeList xnf1 = xe.ChildNodes;
foreach (XmlNode xn2 in xnf1) {
Console.WriteLine(xn2.InnerText); // 顯示子節點文字
}
}
透過這四個步驟,就能完整掌握 XmlDocument 對 XML 節點的增、修、刪、查。它像一條清楚的流水線:SelectSingleNode 定位、CreateElement 建立、SetAttribute 設屬性、AppendChild 掛節點、Save 存回。雖然看似「笨」,但正因為每一步都攤在陽光下,初學者才能踏實理解 XML DOM 的操作邏輯;熟悉之後,再改用 XPath 或 LINQ to XML 就會游刃有餘了。