【问题标题】:How to delete specific nodes from an XElement?如何从 XElement 中删除特定节点?
【发布时间】:2015-01-27 11:10:36
【问题描述】:

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

如果它们包含“条件”节点,我想删除所有“规则”节点。

我创建了一个如下的 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>

如果所有“规则”节点包含“条件”节点,我该如何移除它们?

【问题讨论】:

  • 在删除项目时不能使用 foreach 迭代规则元素。相反,您可以将它们收集在一个列表中,然后使用 for 循环进行迭代并删除它们。

标签: c# .net xml linq-to-xml


【解决方案1】:

你可以试试这个方法:

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

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

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

【讨论】:

    【解决方案2】:

    你可以使用 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, so we can use foreach here
        el.Remove();
    }
    

    【讨论】:

      【解决方案3】:

      我为你做了一个小例子:

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

      【讨论】:

        【解决方案4】:
        passiveLead.DataXml.Descendants("Conditions").Remove();
        

        【讨论】:

        • 您能否为 OP 和未来的读者添加一些额外的解释或参考?
        【解决方案5】:
        var el = xRelation.XPathSelectElement("/Rules/Rule/Conditions");
        while (el != null)
        {
              el.Remove();
              el = xRelation.XPathSelectElement("/Rules/Rule/Conditions");
        }
        

        【讨论】:

          【解决方案6】:

          只是一个想法:

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

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多