Amin Sayed
Amin Sayed

Reputation: 1260

Need an idea for LINQ select query for this XML structure

I'm developing a custom search control and setting its configuration based on this sample XML below. So if the user uses my control in his ASPX page and declares a property in his page as:

<ccl:Search control id='searchtextbox' PageName='Master' /> 

then I need to consider the Pagename name='Master' and set all the properties mentioned under this. Similarly for PageName='SearchResults'

<configuration>
 <Pagename name='Master'>
   <Key id='DefaultText'>Search</Key>
   <Key id='SearchBoxCss'>btn</Key>
   <Key id='ButtonText'>Search</Key>
   <Key id='AutocompleteEnabled'>true</Key>
   <Key id='EnableFilterDropNames'>false</Key>
   <Key id='FilterDropNames'>All Areas;Articles</Key>       
 </Pagename>
 <Pagename name='SearchResults'>
   <Key id='DefaultText'>Search</Key>
   <Key id='SearchBoxCss'>btn</Key>
   <Key id='ButtonText'>Search</Key>
   <Key id='AutocompleteEnabled'>false</Key>
   <Key id='EnableFilterDropNames'>false</Key>
   <Key id='FilterDropNames'>All Areas;Articles;Products</Key>                            
 </Pagename>
</configuration>

Can you please suggest the necessary LINQ code to select based on Master or SearchResults

What I have tried:

var ch = from elem in doc.Descendants("Pagename")
                   where elem.Attribute(XName.Get("name")).Value == "Master"
                   select new
                   {
                       Children = elem.Descendants("Key").Attributes()
                   };

this returns me only the list of attributes and not the necessary values.

Upvotes: 0

Views: 95

Answers (2)

Clueless
Clueless

Reputation: 1200

you can try:

elem.Descendants("PageName").
            Where(element => element.Attribute("Name").Value == "Master").First().
            Descendants().Select(element => element.Value);

meaning-> get the first child with name "Master" and than take the values of all it's children nodes

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

var ch = doc.Descendants("PageName")
            .Where(p => (string)p.Attribute("name") == "Master")
            .Elements("Key")
            .Select(k => new
                         {
                             Id = (string)k.Attribute("id"),
                             Value = k.Value
                         }
            );

Upvotes: 2

Related Questions