Search code examples
c#.netxmllinq-to-xml

How can I delete specific nodes from an XElement?


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.

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();
  }
}

Sample:

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


Solution

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