tags:

views:

257

answers:

2
+1  A: 

You got some small typos, on attribute Id and at item loop. But if you're trying to get all section items into that items collection, you're wrong at design level, as Items should be a Section property, not Document (so you'll need to query your XML twice).

Or, you can to do something like:

var documents =
    (from docs in documentRoot.Descendants("document")
     select new
     {
         Id = (string) docs.Attribute("id"),
         Sections = docs.Elements("section")
     }).ToList();

foreach (var doc in documents)
{
    foreach (var section in doc.Sections)
    {
        Console.WriteLine("SectionId: " + section.Attribute("id"));
        foreach (var item in section.Elements("item"))
        {
            Console.WriteLine("ItemId: " + item.Attribute("id"));
        }
    }
}

Output:

SectionId: id="1.1"
ItemId: id="1.1.1"
ItemId: id="1.1.2"
ItemId: id="1.1.3"
SectionId: id="1.2"
ItemId: id="1.2.1"
ItemId: id="1.2.2"
Rubens Farias
Sorry about typos but still doesnt solve the problem. What I am trying to acheive is that only the items that are children to the each section are returned.
Cragly
@Cragly, I just rewrote my answer, take a look
Rubens Farias
Excellent! works like a charm. Such a simple fix. Must not have been able to see the wood for the trees as spent so long looking at this one. Good man.
Cragly
A: 

Do you want a flat structure ?!?! (from LinqPad)

XElement documentRoot  = XElement.Parse (
@"<root> 
<document id='1'> 
  <section id='1.1'> 
    <item id='1.1.1'></item> 
    <item id='1.1.2'></item> 
    <item id='1.1.3'></item> 
  </section> 
  <section id='1.2'> 
    <item id='1.2.1'></item> 
    <item id='1.2.2'></item> 
  </section> 
</document> 
</root> 
");




var documents = (from docs in documentRoot.Descendants("section") 
                 select new 
                    { 
                        SectionId = (string) docs.Attribute("id"), 
                        Items = docs.Elements("item") 
                    }); 
 documents.Dump();

This gives

2 SectionId items that containes Xelements with related items

salgo60
Thanks for the post but what I would idealy like is to be able to access those contained item XElements and assign them to the Items property of the object so I get an IEnumerable<XElement> of items associated with its specific section.
Cragly
Can you give an example of the datastructure you would like to have. Why XElement instead of a type?!?!
salgo60