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

LINQ to XML 進階:查詢、更新、刪除與函數式建構實戰

     編輯:關於.NET

查詢:尋找具特定屬性的元素

XElement root = XElement.Load("PurchaseOrder.xml");
IEnumerable<XElement> billingAddresses = 
    from el in root.Elements("Address")
    where (string)el.Attribute("Type") == "Billing"
    select el;

foreach (XElement el in billingAddresses) Console.WriteLine(el);

修改 XML 樹的兩種範式

1. 就地修改

傳統方式:載入 → 修改節點/屬性 → 儲存。

XElement root = XElement.Load("Data.xml");
foreach (XAttribute att in root.Attributes()) {
    root.Add(new XElement(att.Name, (string)att));
}
root.Attributes().Remove();
// 結果:屬性轉為子元素

2. 函數式建構

將修改視為轉換:從來源樹查詢、轉換、建構新樹。

XElement root = XElement.Load("Data.xml");
XElement newTree = new XElement("Root",
    root.Element("Child1"),
    from att in root.Attributes()
    select new XElement(att.Name, (string)att)
);
Console.WriteLine(newTree);

優勢:大量轉換時程式碼更易維護、可組合;代價:建立較多短命物件。開發效率與執行效能的權衡由團隊決定。

新增元素、屬性與節點

方法說明
Add在 XContainer 子內容末尾新增
AddFirst在 XContainer 子內容開頭新增
AddAfterSelf在 XNode 之後新增同級內容
AddBeforeSelf在 XNode 之前新增同級內容
XElement xmlTree = new XElement("Root", new XElement("Child1", 1), ...);
xmlTree.Add(new XElement("NewChild", "new content"));
xmlTree.Add(from el in srcTree.Elements() where (int)el > 3 select el);
// 若來源不存在(如 Child9),不拋例外、不新增

修改元素、屬性與節點

XElement 關鍵方法

方法用途
SetElementValue(name, value)設定子元素值;不存在則建立;值為 null 則移除
SetAttributeValue(name, value)設定屬性值;不存在則建立;值為 null 則移除
ReplaceAll(content)替換所有子節點與屬性
Value / SetValue替換元素文字內容

SetElementValue / SetAttributeValue 範例

XElement root = new XElement("Root");
root.SetElementValue("Ele1", 1);
root.SetElementValue("Ele2", 2);
root.SetElementValue("Ele3", 3);
// 123

root.SetElementValue("Ele2", 22); // 修改
root.SetElementValue("Ele3", null); // 移除
// 122

XNode.ReplaceWith:替換節點本身

XElement child3 = xmlTree.Element("Child3");
child3.ReplaceWith(new XElement("NewChild", "new content"));
// Child3 被 NewChild 取代

刪除元素、屬性與節點

關鍵規則:移除集合時,必須先具體化為清單(ToList())或使用 Remove() 擴充方法,否則延遲執行導致迭代器失效。

XElement root = XElement.Parse(@"");

root.Element("Child1").Element("GrandChild1").Remove(); // 單一元素
root.Element("Child2").Elements().ToList().ForEach(e => e.Remove()); // 具體化後移除
root.Element("Child3").Elements().Remove(); // 使用擴充方法 Remove()
延遲執行移除集合的陷阱
延遲執行導致移除集合時的常見 Bug

總結

LINQ to XML 提供豐富的記憶體樹操作 API:

  • 查詢:標準 LINQ 語法,強型別、可組合。
  • 修改:就地修改適合小幅變更;函數式建構適合大規模轉換。
  • 新增/刪除:Add/AddFirst/AddAfterSelf/AddBeforeSelf 靈活控制位置;SetElementValue/SetAttributeValue 簡化名值對維護。
  • 刪除集合:永遠先 ToList() 或用 Remove() 擴充方法。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved