How to delete specific nodes from an XElement?

How to delete specific nodes from an XElement?

You can try this approach:

var nodes = xRelation.Elements().Where(x => x.Element("Conditions") != null).ToList();

foreach(var node in nodes)
    node.Remove();

Basic idea: you can't delete elements of collection you're currently iterating.
So first you have to create list of nodes to delete and then delete these nodes.

研究发现,只有Elements()这种筛选的 IEnumerable<XElement>才有问题,没法进行Remove。

但是如果是Elements("add")或Elements("remove"),可以不用ToList()就正常删除的

另外还发现,如果有2个相同的节点,通过Elements("add")操作where过滤出来之后,只能删除一个

  <add assembly="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

  <add assembly="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

只有用了ToList(),然后再遍历,才可以正常删除

原文地址:https://www.cnblogs.com/chucklu/p/14756834.html