傳統 XmlDocument (DOM) API 冗長、非直觀,建構 XML 需大量 CreateElement/AppendChild 呼叫。LINQ to XML (System.Xml.Linq) 利用 C# 3.0 語言特性(物件初始化器、Lambda、匿名型別),提供函數式建構、整合查詢與輕量型別,讓 XML 程式碼如同資料結構般清晰可讀。
巢狀建構子完美對應 XML 階層:
XElement people = new XElement("people",
new XElement("person",
new XElement("firstname", "Bob"),
new XElement("lastname", "Willam"),
new XElement("age", "50"),
new XElement("phone", "012345", new XAttribute("type", "mobile")),
new XElement("phone", "987654", new XAttribute("type", "home")),
new XElement("address",
new XElement("country", "USA"),
new XElement("city", "LA")
)
)
);
對比 XmlDocument 版本,程式碼行數減少 70%,結構一目瞭然。
XDocument doc = XDocument.Load("peopleData.xml");
var foundPeople = doc.Descendants("person")
.Where(p => Convert.ToInt32(p.Element("age").Value) > 20)
.Select(p => new {
Name = p.Element("firstname").Value + " " + p.Element("lastname").Value,
Age = Convert.ToInt32(p.Element("age").Value),
Phone = p.Elements("phone").Select(ph => ph.Value).ToArray()
});
foreach (var person in foundPeople) {
Console.WriteLine($"{person.Name}, {person.Age}, Phones: {string.Join(",", person.Phone)}");
}
LINQ to XML 允許直接對 XElement 載入/解析,無須先建立 XmlDocument:
// 從字串
XElement fromString = XElement.Parse(xmlContent);
// 從檔案
XElement fromFile = XElement.Load(@"D:\test.xml"); // 多載支援 Stream、TextReader、XmlReader
傳統 DOM 中,節點必須屬於某個 XmlDocument,跨 Document 移動需 ImportNode。LINQ to XML 中,XElement、XAttribute 獨立存在,可自由組合:
XElement person = new XElement("person");
XAttribute age = new XAttribute("age", "50"); // 屬性必須有值,無無參建構子
person.Add(age);
需 XML 宣告、處理指令、註解時使用 XDocument:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("This is the comments"),
new XProcessingInstruction("test", "test processing instruction"),
new XElement("people")
);
doc.Save("test.xml");