简体   繁体   中英

LINQ to XML recursively remove elements - C#

I have the following XML:

<Root>
 <Section name="xyz" />
 <Section name="abc">
   <Section name="def" />
 </Section>
 <Section name="abc">
   <Section name="def">
     <Section name="xyz" />
     <Section name="abc" />
     <Section name="xyz">
       <Section name="xyz" />
     </Section>
  </Section>
</Section>
</Root>

I have the XDocument representation of the XML. How I do traverse through the tree and remove all elements with say abc

That's really easy :)

doc.Descendants("Section")
   .Where(x => (string) x.Attribute("name") == "xyz")
   .Remove();

Gotta love LINQ to XML...

EDIT: I've just tried it with your sample XML, and this was the result afterwards:

<Root>
  <Section name="abc">
    <Section name="def" />
  </Section>
  <Section name="abc">
    <Section name="def">
      <Section name="abc" />
    </Section>
  </Section>
</Root>

Please let me know if that's not what you were expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM