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

问题描述 投票:0回答:6

我创建了一个带有节点的 XElement,其 XML 如下。

我想删除所有包含“conditions”节点的“Rule”节点。

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

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

样品:

<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>

如果所有“Rule”节点包含“conditions”节点,如何删除它们?

c# .net xml linq-to-xml
6个回答
20
投票

你可以尝试这个方法:

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

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

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


15
投票

您可以使用LINQ

xRelation.Elements()
     .Where(el => el.Elements("Conditions") == null)
     .Remove();

或者创建要删除的节点的副本,然后删除它们(以防第一种方法不起作用):

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

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

3
投票
  passiveLead.DataXml.Descendants("Conditions").Remove();

这将删除与 XML 文档的名称“条件”匹配的所有后代元素。


2
投票

我为你做了一个小例子:

XDocument document = XDocument.Parse(GetXml());
var rulesNode = document.Element("Rules");
if (rulesNode != null)
{
    rulesNode.Elements("Rule").Where(r => r.Element("Conditions") != null).Remove();
}

1
投票
var el = xRelation.XPathSelectElement("/Rules/Rule/Conditions");
while (el != null)
{
      el.Remove();
      el = xRelation.XPathSelectElement("/Rules/Rule/Conditions");
}

-1
投票

只是一个想法:

反转 Linq“条件”,您将得到一个没有“规则”节点的列表

© www.soinside.com 2019 - 2024. All rights reserved.