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

C# Xml 移除指定節點:XPath 精準刪除

     編輯:關於C#

XML 範例

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="李1" ISBN="2-3645-4">
    <title>Net從入門到精通</title>
    <author>李大蒜</author>
    <price>58.3</price>
  </book>
  <book genre="李2" ISBN="2-3631-4">
    <title>CS從入門到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </book>
  <book genre="李3" ISBN="2-3631-4">
    <title>CS從入門到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </book>
</bookstore>

核心方法:依屬性值刪除節點


/// 
/// 刪除指定 XPath 下、屬性值符合條件的節點
/// 
/// XML 檔案完整路徑
/// 目標節點 XPath(如 "//book")
/// 要比對的屬性名稱(如 "genre")
/// 要比對的屬性值(如 "李2")
public static void RemoveNodesByAttribute(string xmlFilePath, string xpath, 
    string attributeName, string attributeValue)
{
    var doc = new XmlDocument();
    doc.Load(xmlFilePath);

    // 選取所有符合 XPath 的節點
    var nodes = doc.SelectNodes(xpath);
    if (nodes == null) return;

    // 反向迴圈避免刪除時索引錯亂
    for (int i = nodes.Count - 1; i >= 0; i--)
    {
        var node = nodes[i];
        var attr = node.Attributes?[attributeName];
        if (attr != null && attr.Value == attributeValue)
        {
            node.ParentNode?.RemoveChild(node);
        }
    }

    doc.Save(xmlFilePath);
}

使用範例


// 刪除 genre="李2" 的 book 節點
RemoveNodesByAttribute(@"E:\bookstore.xml", "//book", "genre", "李2");

其他常見刪除場景

需求XPath 範例說明
刪除特定 ISBN 的書//book[@ISBN='2-3631-4']直接在 XPath 謂詞中篩選
刪除所有 price > 60 的書//book[price > 60]XPath 支援數值比較
刪除特定作者的書//book[author='候捷']子元素文字比對
刪除整個 bookstore 下的所有 book/bookstore/book保留根節點

直接用 XPath 刪除(更簡潔)


public static void RemoveNodesByXPath(string xmlFilePath, string xpath)
{
    var doc = new XmlDocument();
    doc.Load(xmlFilePath);
    
    var nodes = doc.SelectNodes(xpath);
    if (nodes != null)
    {
        for (int i = nodes.Count - 1; i >= 0; i--)
            nodes[i].ParentNode?.RemoveChild(nodes[i]);
    }
    doc.Save(xmlFilePath);
}

// 使用:刪除所有 ISBN="2-3631-4" 的 book
RemoveNodesByXPath(@"E:\bookstore.xml", "//book[@ISBN='2-3631-4']");

注意事項

  1. 命名空間:XML 若有預設命名空間,需使用 XmlNamespaceManager 註冊前綴才能正確選取
  2. 效能:大型 XML(>10MB)建議使用 XmlReader + XmlWriter 流式處理,避免完整載入 DOM
  3. 編碼:doc.Save 會保留原檔案宣告的編碼,若需變更需手動處理 XmlDeclaration
  4. 備份:生產環境刪除前建議先備份原檔
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved