載入 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 保留
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");
原文連結:https://www.bianceng.cn/Programming/csharp/201410/45570.htm