XML 範例
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="李2紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
<book genre="李贊紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>小六</author>
<price>58.3</price>
</book>
<book45 genre="李贊紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>大黃</author>
<price>58.3</price>
</book45>
</bookstore>
完整操作範例
using System;
using System.Xml;
public class XmlDemo
{
public static void Run()
{
var doc = new XmlDocument();
doc.Load(@"E:\bookstore.xml");
// 1. 取得根節點
var root = doc.DocumentElement; // bookstore
Console.WriteLine($"根節點: {root.Name}");
// 2. 遍歷所有子節點(含不同名稱的 book/book45)
foreach (XmlNode node in root.ChildNodes)
{
if (node.NodeType != XmlNodeType.Element) continue;
Console.WriteLine($"\n節點: {node.Name}");
// 2.1 讀取屬性
if (node.Attributes != null)
{
foreach (XmlAttribute attr in node.Attributes)
Console.WriteLine($" 屬性: {attr.Name} = {attr.Value}");
}
// 2.2 讀取子元素
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
Console.WriteLine($" 子元素: {child.Name} = {child.InnerText}");
}
// 3. 修改屬性範例:將 genre 含「紅」的改為「綠」
if (node.Attributes?["genre"]?.Value.Contains("紅") == true)
{
node.Attributes["genre"].Value = node.Attributes["genre"].Value.Replace("紅", "綠");
Console.WriteLine($" -> 已修改 genre: {node.Attributes["genre"].Value}");
}
// 4. 新增子元素範例:加入 標準出版社
var pubElem = doc.CreateElement("publisher");
pubElem.InnerText = "標準出版社";
node.AppendChild(pubElem);
Console.WriteLine($" -> 已新增 publisher");
}
// 5. 新增整個 book 節點
var newBook = doc.CreateElement("book");
newBook.SetAttribute("genre", "新類別");
newBook.SetAttribute("ISBN", "9-9999-9");
var title = doc.CreateElement("title");
title.InnerText = "C# XML 實戰";
newBook.AppendChild(title);
var author = doc.CreateElement("author");
author.InnerText = "張三";
newBook.AppendChild(author);
var price = doc.CreateElement("price");
price.InnerText = "99.9";
newBook.AppendChild(price);
root.AppendChild(newBook);
Console.WriteLine("\n-> 已新增完整 book 節點");
// 6. 儲存變更
doc.Save(@"E:\bookstore_modified.xml");
Console.WriteLine("\n已儲存至 bookstore_modified.xml");
}
}
關鍵 API 速查
| 操作 | 方法/屬性 | 說明 |
| 載入檔案 | doc.Load(path) | 從檔案/Stream/Url 載入 |
| 載入字串 | doc.LoadXml(xmlString) | 從字串載入 |
| 根節點 | doc.DocumentElement | 直接取得根元素 |
| 選取節點 | node.SelectNodes(xpath) | 回傳 XmlNodeList |
| 選取單一節點 | node.SelectSingleNode(xpath) | 回傳 XmlNode 或 null |
| 建立元素 | doc.CreateElement(name) | 需用 doc 建立才屬於同一文件 |
| 建立屬性 | doc.CreateAttribute(name) / elem.SetAttribute(name, value) | SetAttribute 更簡便 |
| 建立文字節點 | doc.CreateTextNode(text) | 或直接設 elem.InnerText |
| 新增子節點 | parent.AppendChild(child) | 加在最後 |
| 插入節點 | parent.InsertBefore(new, ref) / InsertAfter | 指定位置插入 |
| 移除節點 | parent.RemoveChild(child) | |
| 修改文字 | node.InnerText = "新值" | 會移除原有子節點 |
| 儲存 | doc.Save(path/stream/writer) | |
XPath 常用語法
// 所有 book 節點(任意層級)
//book
// 根節點下的直接子節點 book
/bookstore/book
// 屬性 genre 為 "李2紅" 的 book
//book[@genre='李2紅']
// 含有 author 子元素且文字為 "候捷" 的 book
//book[author='候捷']
// price 數值大於 50 的 book
//book[price > 50]
// 最後一個 book
//book[last()]
// 前兩個 book
//book[position() <= 2]
進階提示
- 命名空間:XML 有
xmlns 時,必須用 XmlNamespaceManager 註冊前綴,XPath 才能匹配
- 大型 XML:>10MB 建議
XmlReader (唯讀) / XmlWriter (寫入) 流式處理
- 驗證:
doc.Schemas.Add(...) + doc.Validate(...) 可依 XSD 驗證
- LINQ to XML:新專案推薦
XDocument / XElement,語法更現代、支援 LINQ 查詢