How to delete specific nodes from an XElement?

后端 未结 6 405
时光取名叫无心
时光取名叫无心 2021-01-11 18:49

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.

6条回答
  •  孤城傲影
    2021-01-11 19:12

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

提交回复
热议问题