title: LINQ to XML Selecting Child Elements
body: <p>I am trying to extract information from an XML file into an object using LINQ to XML. Although I can return the document and section Id attributes I cannot get access to the Items for each section element, it returns an IEnumerable of all the items in the document. I know this is correct as I’m calling Descendants but am struggling to get it to return only the child items of each section element. Can anybody help?</p>
  
  <p><strong>XML Document</strong></p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;root&gt;
  &lt;document id="1"&gt;
    &lt;section id="1.1"&gt;
      &lt;item id="1.1.1"&gt;&lt;/item&gt;
      &lt;item id="1.1.2"&gt;&lt;/item&gt;
      &lt;item id="1.1.3"&gt;&lt;/item&gt;
    &lt;/section&gt;
    &lt;section id="1.2"&gt;
      &lt;item id="1.2.1"&gt;&lt;/item&gt;
      &lt;item id="1.2.2"&gt;&lt;/item&gt;
    &lt;/section&gt;
  &lt;/document&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p><strong>LINQ Query</strong></p>
  
  <pre><code>XElement documentRoot = XElement.Load("document.xml");
  var documents = (from docs in documentRoot.Descendants("document")
                   select new
                      {
                          Id = (string) docs.Attribute("id"),
                          Sections = docs.Elements("section"),
                          Items = docs.Elements("section").Elements("item")
                      }).ToList();
  
  foreach(var doc in documents)
  {
      foreach(var section in doc.Sections)
      {
          Console.WriteLine("SectionId: " + section.Attribute("Id"));  
          foreach(var item in doc.Items)
          {
              Console.WriteLine("ItemId: " + section.Attribute("Id"));
          }
      }
  }
  </code></pre>