how to remove Xelement without its children node using LINQ?

后端 未结 4 945
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 02:49

Here is my XML,


    
      
           
    
    
         


        
4条回答
  •  余生分开走
    2021-01-14 03:31

    To improve Mike's useful answer slightly.

    The reason you can't just iterate Descendants once is because AddAfterSelf() creates copies. After the first removal you're iterating children of the removed element rather than their replacements in the document.

    However, if you iterate them backwards, then any copied children will have already been processed, so you can get away with a single pass:

    foreach(var x in xdoc.Descendants("x").Reverse())
    {
        x.AddAfterSelf(x.Nodes());
        x.Remove();
    }
    

提交回复
热议问题