LINQ to XML get elements in c#

I have this xml structure:

<section id="section1">  <section id="section2"/>  <section id="section3"/> </section> <section id="section4"/> 

How can I get the id’s of the sections in section1. The result should be section2 and section3.

I tried this method but I get the result "section1":

var sectionsinsection1 = from x in xdocument.Descendants("section")                          where x.Attribute("id").Value == "section1"                          select x.Attribute("id").Value; 
Add Comment
1 Answer(s)

Objects of XDocument type need to have a root, so I’m checking for the parent of sections other than document root.

var sectionsinsection1 = from s in xdocument.Descendants("section")                          where s.Parent != s.Document.Root                                 && s.Parent.Attribute("id").Value == "section1"                          select s.Attribute("id").Value; 
Answered on July 17, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.