satya
satya

Reputation: 2607

Converting an xml into list of anonymous object

I have an xml which contain the language details like

<LanguageList>
   <Language code = "EN-US" name = "English - United Sates"></Language>
   <Language code = "EN-UK" name = "English - United Kingdom"></Language>
    --
    --
</LanguageList>

I want to convert this into a list of anonymous objects where each object contains two fields code and name.

I tried with following linq expression

 var anonList = (from u in xDoc.Descendants("LanguageList").DescendantNodes()
                   select u).ToList();

this is giving all nodes under LanguageList like

   <Language code = "EN-US" name = "English - United Sates"></Language>
   <Language code = "EN-UK" name = "English - United Kingdom"></Language>

I tried adding some where clauses and other ways.. but not able to get it. can anyone help

Thanks in advance..

Upvotes: 0

Views: 661

Answers (3)

har07
har07

Reputation: 89285

Building on the code you have :

var anonList = (from u in xDoc.Descendants("LanguageList")
                              .Elements("Language")
                select new 
                       { 
                          Name = (string)u.Attribute("name"),
                          Code = (string)u.Attribute("code")
                       }
                ).ToList();
  1. Use Elements() instead of DescendantNodes() to get children elements. 2. You can cast an XAttribute directly to string.

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

You need to get the attribute of each node and create the anonymous object. Something like this:

var listOfLanguages = xDoc.Descendants("LanguageList").Descendants()
                          .Select(l => new
                          {
                              Name = l.Attribute("name").Value,
                              Code = l.Attribute("code").Value
                          });

Upvotes: 1

Peter Duniho
Peter Duniho

Reputation: 70652

Instead of selecting "u", select something like "new { Code = u.Attribute("code").Value, Name = u.Attribute("name").Value }".

Upvotes: 0

Related Questions