开发者

remove sub elements from xml using LINQ to XML

开发者 https://www.devze.com 2023-02-12 12:11 出处:网络
I want to remove sub elements from an XML doc using LINQ to XML. sample XML: <MainElement> <otherelement />

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

精彩评论

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