0
Answer

Linq to XML - Projecting an Object hierarchy

tom m

tom m

16y
5.6k
1

Hi,

I am having trouble getting my head round a few Linq to XML ideas.

Here is my example scenario that I am using.  I have a simple XML file representing a todo list.  There can be multiple list and each list is divided into sections and subsections. For example:

<list name ="PhD Research">

    <section name= "Experiment">

         <subsection name = "Measurement>

              <task>

                  <desc> etc....

 

Now as an example I want to display the contents of a specific list - its hierarchy - on the screen.  My approach is to query the xml file.  At the moment lets limit this to all of the section and subsections within a list.  The following code is what I have put together - but I am not happy with it ...

(nb assume doc is a XDocument and listName is a string)

var availableLists = doc.Descendants("list").Where(i=>i.Attribute("name").Value == listName);

var availableSections = availableLists.Descendants("section");

var sections =

   availableSections.Select(

         section=> new

         {

            SectionName = section.Attribute("name").Value

         }

      );

var availableSubsections = availableSections.Descendants("subsection");

var subsections = availableSubsections.Select(

   subsection=> new

   {

      SubsectionName = subsection.Attribute("name").Value

   }

);

foreach(var section in sections){

   Console.WriteLine(section.SectionName);

}

foreach(var sub in subsections){

   Console.WriteLine(sub.SubsectionName);

}

The foreach loops output the section and subsection name correctly; however this isn't quite what I want to achieve.  I guess what I am after is transforming the xml into a hierarchy of objects. I have tried a few ways of doing this - adding subquerys to descendants of availableSections in the 1st query etc. - without success. 

At the moment my approach is clearly flawed.  Can anyone give me some guidance about how I might go about this?

Many thanks