How to remove Xelement without its node children using LINQ?

Here is my XML,

<A>
    <B  id="ABC">
      <C name="A" />
      <C name="B" />     
    </B>
    <X>
     <B id="ZYZ">
      <C name="A" />
      <C name="B" />
     </B>
    </X>
</A>

I use the following code to remove a node without removing its descents / children, <X>

XDocument doc = XDocument.Load("D:\\parsedXml.xml");
doc.Descendants("A").Descendants("X").Remove();

But deletes the entire block . <X>

Expected Result:

<A>
    <B  id="ABC">
      <C name="A" />
      <C name="B" />     
    </B>
     <B id="ZYZ">
      <C name="A" />
      <C name="B" />
     </B>
</A>
+3
source share
2 answers
var x = doc.Root.Element("X");
x.Remove();
doc.Root.Add(x.Elements());
+5
source

An approved answer always adds children to the end of the document. If you need to delete the entry in the middle of the document and leave the children where they are sitting, follow these steps:

x.AddAfterSelf(x.Nodes());
x.Remove();

The following code deletes all nodes <x>, keeping the children in the right place:

while (doc.Descendants("x").Count() > 0)
{
    var x = doc.Descendants("x").First();
    x.AddAfterSelf(x.Nodes());
    x.Remove();
}
+2
source

All Articles