.NET 的 XmlDocument 把整份 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>
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("bookstore.xml");
// 找到 <bookstore> 這個根節點
XmlNode root = xmlDoc.SelectSingleNode("bookstore");
// 建立 <book> 節點並設定屬性
XmlElement xe1 = xmlDoc.CreateElement("book");
xe1.SetAttribute("genre", "李贊紅");
xe1.SetAttribute("ISBN", "2-3631-4");
// 建立子節點 title
XmlElement xesub1 = xmlDoc.CreateElement("title");
xesub1.InnerText = "CS從入門到精通";
xe1.AppendChild(xesub1);
// 建立子節點 author
XmlElement xesub2 = xmlDoc.CreateElement("author");
xesub2.InnerText = "候捷";
xe1.AppendChild(xesub2);
// 建立子節點 price
XmlElement xesub3 = xmlDoc.CreateElement("price");
xesub3.InnerText = "58.3";
xe1.AppendChild(xesub3);
// 掛到根節點下並存檔
root.AppendChild(xe1);
xmlDoc.Save("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>
<book genre="李贊紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>
需求:把 genre 屬性值為「李贊紅」的節點改成「update李贊紅」,並把它的 author 子節點文字改為「亞勝」。
// 取得 bookstore 底下所有子節點
XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode xn in nodeList)
{
// 轉型成 XmlElement 才能操作屬性
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");
最後的結果:
<?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>
<book genre="update李贊紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>亞勝</author>
<price>58.3</price>
</book>
</bookstore>
SelectSingleNode 支援 XPath,用它定位節點比一層層寫 foreach 簡潔得多,例如 xmlDoc.SelectSingleNode("//book[@genre='李贊紅']/author")。SetAttribute/GetAttribute,文字內容用 InnerText,兩者不要混用。Save 會丟出 IO 例外。XDocument/XElement(LINQ to XML)通常更輕便。