Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 333
user2837961 Avatar asked Jan 27 '15 11:01

user2837961


People also ask

How to remove element from XElement in c#?

Look for the element I want to delete. XElement child1 = xmlTree2. Element(“Child1”); Delete it.

How do you delete an element in XML?

Remove a Text Node xml is loaded into xmlDoc. Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.

What is XElement C#?

The XElement class represents an XML element in XLinq. The code creaes a root node called Authors and adds children Author nodes. The XAttribute class represents an attribute of an element. XElement. Save method saves the contents of XElement to a XML file.

How do you make XElement?

var el = new XElement("name", value);


3 Answers

You can use Linq:

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

Or create a copy of the nodes to delete, and delete them after (in case the first method doesn't work):

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();
}
like image 178
Kilazur Avatar answered Oct 17 '22 04:10

Kilazur


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.

like image 38
Andrey Korneyev Avatar answered Oct 17 '22 03:10

Andrey Korneyev


passiveLead.DataXml.Descendants("Conditions").Remove();
like image 23
user2700757 Avatar answered Oct 17 '22 04:10

user2700757