如何从XElement中删除特定节点?

use*_*961 9 .net c# xml linq-to-xml

我创建了一个带有节点的XElement,其中包含XML,如下所示.

我想删除所有" 规则 "节点,如果它们包含" 条件 "节点.

我创建一个for循环,如下所示,但它不会删除我的节点

foreach (XElement xx in xRelation.Elements())
{
  if (xx.Element("Conditions") != null)
  {
    xx.Remove();
  }
}
Run Code Online (Sandbox Code Playgroud)

样品:

<Rules effectNode="2" attribute="ability" iteration="1">
    <Rule cause="Cause1" effect="I">
      <Conditions>
        <Condition node="1" type="Internal" />
      </Conditions>
    </Rule>
    <Rule cause="cause2" effect="I">
      <Conditions>
        <Condition node="1" type="External" />
      </Conditions>
    </Rule>
</Rules>
Run Code Online (Sandbox Code Playgroud)

如果它们包含" 条件 "节点,如何删除所有" 规则 "节点?

And*_*yev 14

你可以尝试这种方法:

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

foreach(var node in nodes)
    node.Remove();
Run Code Online (Sandbox Code Playgroud)

基本思路:您无法删除当前正在迭代的集合元素.
首先,您必须创建要删除的节点列表,然后删除这些节点.


Kil*_*zur 7

你可以使用Linq:

xRelation.Elements()
     .Where(el => el.Elements("Conditions") == null)
     .Remove();
Run Code Online (Sandbox Code Playgroud)

或者创建要删除的节点的副本,并在之后删除它们(如果第一种方法不起作用):

List nodesToDelete = xRelation.Elements().Where(el => el.Elements("Conditions") == null).ToList();

foreach (XElement el in nodesToDeletes)
{
    // Removes from its parent, but not nodesToDelete, so we can use foreach here
    el.Remove();
}
Run Code Online (Sandbox Code Playgroud)