How to delete specific nodes from an XElement?
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();
}
I've 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();
}
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.