首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

LINQ to XML 實戰:從建構、查詢到載入的現代化 XML 程式設計

     編輯:關於.NET

為什麼選擇 LINQ to XML?

傳統 XmlDocument (DOM) API 冗長、非直觀,建構 XML 需大量 CreateElement/AppendChild 呼叫。LINQ to XML (System.Xml.Linq) 利用 C# 3.0 語言特性(物件初始化器、Lambda、匿名型別),提供函數式建構、整合查詢與輕量型別,讓 XML 程式碼如同資料結構般清晰可讀。

建構 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%,結構一目瞭然。

查詢 XML:整合 LINQ 查詢

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)}");
}

載入 XML:擺脫 Document 束縛

LINQ to XML 允許直接對 XElement 載入/解析,無須先建立 XmlDocument:

// 從字串
XElement fromString = XElement.Parse(xmlContent);

// 從檔案
XElement fromFile = XElement.Load(@"D:\test.xml"); // 多載支援 Stream、TextReader、XmlReader

元素獨立於 Document:更自然的程式模型

傳統 DOM 中,節點必須屬於某個 XmlDocument,跨 Document 移動需 ImportNode。LINQ to XML 中,XElement、XAttribute 獨立存在,可自由組合:

XElement person = new XElement("person");
XAttribute age = new XAttribute("age", "50"); // 屬性必須有值,無無參建構子
person.Add(age);

仍支援 XDocument:完整文件功能

需 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");

核心優勢總結

  • 可讀性:建構語法即文件結構。
  • 查詢整合:標準 LINQ 查詢 XML,型別安全、編譯檢查。
  • 效能:輕量型別、無 DOM 額外負擔。
  • 命名空間簡化:自動解析前綴,預設使用預設命名空間序列化。

參考:.NET Language-Integrated Query for XML Data

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved