how to remove Xelement without its children node using LINQ?

喜欢而已 提交于 2019-12-10 10:15:13

问题


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


来源:https://stackoverflow.com/questions/21730252/how-to-remove-xelement-without-its-children-node-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!