如何从XElement删除特定节点? [英] How to delete specific nodes from an XElement?

查看:680
本文介绍了如何从XElement删除特定节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个XElement,其节点具有XML,如下所示.

I have created a XElement with node which has XML as below.

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

I want to remove all the "Rule" nodes if they contain "conditions" node.

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

I create a for loop as below but it does not delete my nodes

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>

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

How can I remove all the "Rule" nodes if they contain "conditions" node?

推荐答案

您可以尝试以下方法:

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.

这篇关于如何从XElement删除特定节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆