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

C# XmlDocument 依節點名稱與值刪除特定子節點完整實作

     編輯:關於C#

核心邏輯

載入 XML → 找到父節點 → 遍歷子節點 → 比對 Name 與 Value → 移除符合節點 → 儲存。

實作代碼

public static void RemoveXmlNodesByNameValue(string filePath, string parentXPath, string childName, string childValue)
{
    if (!File.Exists(filePath)) throw new FileNotFoundException("XML 檔案不存在", filePath);

    var doc = new XmlDocument();
    doc.Load(filePath);

    XmlNode parent = doc.SelectSingleNode(parentXPath);
    if (parent == null)
    {
        Console.WriteLine($"找不到父節點: {parentXPath}");
        return;
    }

    // 由後往前刪除,避免索引位移
    for (int i = parent.ChildNodes.Count - 1; i >= 0; i--)
    {
        XmlNode child = parent.ChildNodes[i];
        if (child.Name == childName && child.InnerText == childValue)
        {
            parent.RemoveChild(child);
        }
    }

    doc.Save(filePath);
}

使用範例



  
    30
    3
    60  
  


// 呼叫
RemoveXmlNodesByNameValue(@"C:\Config.xml", "/Root/Settings", "Item", "60");
// 結果: 只有 Value=60 的 Item 被移除,Value=30 保留

進階版:支援 XPath 完整比對、屬性值比對

public static void RemoveNodesAdvanced(string filePath, string xpath, string attrName = null, string attrValue = null, string innerText = null)
{
    var doc = new XmlDocument();
    doc.Load(filePath);

    XmlNodeList nodes = doc.SelectNodes(xpath);
    if (nodes == null) return;

    // 收集要刪除的節點 (不能在 foreach 中直接 RemoveChild)
    var toRemove = new List();
    foreach (XmlNode node in nodes)
    {
        bool match = true;
        if (attrName != null)
        {
            XmlAttribute attr = node.Attributes?[attrName];
            if (attr == null || attr.Value != attrValue) match = false;
        }
        if (innerText != null && node.InnerText != innerText) match = false;

        if (match) toRemove.Add(node);
    }

    foreach (var node in toRemove)
        node.ParentNode?.RemoveChild(node);

    doc.Save(filePath);
}

// 使用範例
// 刪除 Key="Timeout" 且 Value="60" 的 Item
RemoveNodesAdvanced(@"C:\Config.xml", "/Root/Settings/Item", "Key", "Timeout", "60");

注意事項

  • XmlDocument.Save 會覆寫原檔,建議先備份或寫入暫存檔再替換。
  • 命名空間: XML 若有預設命名空間,XPath 需註冊 `XmlNamespaceManager` 並加前綴查詢。
  • 大檔案: `XmlDocument` 全載入記憶體,>50MB 建議改用 `XmlReader` + `XmlWriter` 串流轉換。
  • 並發: 多執行緒同時讀寫同一 XML 檔需加鎖 (`lock` 或 `FileShare`)。

參考資源

原文連結:https://www.bianceng.cn/Programming/csharp/201410/45570.htm

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