Nick
Nick

Reputation: 7525

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

Upvotes: 0

Views: 706

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 7

Related Questions