开发者

remove sub elements from xml using LINQ to XML

I want to remove sub elements from an XML doc using LINQ to XML.

sample XML:

<MainElement>
<otherelement />
<removeElement att='1'>
<removeElement att='2'>
<removeElement att='3'>
<removeElement att='4'>
</MainElement>

I want the output to be

<MainElement>
<otherelement />
<removeElement att='2'>
</MainElement>

The structure(Schema) should remain as it is, and the selected element should remain in the XML doc.

the queries that I tried helps me开发者_运维知识库 find that element from the XML, however, how do I maintain the XML structure


Write a query to find the nodes that you want to remove and remove them.

XDocument doc = ...;
doc.Root
   .Elements("removeElement")
   .Where(e => (int)e.Attribute("att") != 2)
   .Remove(); // removes all elements in this query
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜