how to remove Xelement without its children node u

2019-05-10 13:23发布

问题:

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'm using following code to remove <X> node without deleting its descents/childrens,

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

But is removing entire <X> block.

Expected output :

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

回答1:

var x = doc.Root.Element("X");
x.Remove();
doc.Root.Add(x.Elements());


回答2:

Approved answer will always add children to the end of document. If you need to remove entry in the middle of the document and keep children where they sit, do following:

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

Following code removes all <x> nodes keeping children in the correct place:

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