简体   繁体   中英

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..

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
                          });

而不是选择“ u”,而是选择“ new {Code = u.Attribute(“ code”)。Value,Name = u.Attribute(“ name”)。Value}“)。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM