How to remove specific nodes from XElement?

I created an XElement with a node that has XML, as shown below.

I want to delete all the "Rule" nodes if they contain the "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(); } } 

Example:

 <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 to delete all nodes "Rule" if they contain "conditions" node?

+6
source share
5 answers

You can try this approach:

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

The basic idea: you cannot delete the elements of the collection that you are iterating now.
Therefore, you first need to create a list of nodes to delete, and then delete these nodes.

+13
source

You can use Linq:

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

Or create a copy of the nodes to be deleted and delete them after (in case the first method does not 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(); } 
+5
source

I made a small example for you:

 XDocument document = XDocument.Parse(GetXml()); var rulesNode = document.Element("Rules"); if (rulesNode != null) { rulesNode.Elements("Rule").Where(r => r.Element("Conditions") != null).Remove(); } 
+2
source
 passiveLead.DataXml.Descendants("Conditions").Remove(); 
+2
source
 var el = xRelation.XPathSelectElement("/Rules/Rule/Conditions"); while (el != null) { el.Remove(); el = xRelation.XPathSelectElement("/Rules/Rule/Conditions"); } 
0
source

Source: https://habr.com/ru/post/1211993/


All Articles