简体   繁体   中英

How to create object from an xml

How do you create an object by XElement ? I can create a list, but I want a single object and not a list.

Here is my code:

XElement elem = XElement.Load(path);
var myList = from n in elem.Descendants("NodeNumber1")
             select new
             {
                 Name = n.Attribute("Name").Value,
                 MyObj = from o in n.Descendants("NodeChild")
                         select new
                         {
                             var1 = o.Descendants("var1").FirstOrDefault().Value,
                             var2 = o.Descendants("var2").FirstOrDefault().Value,
                         }
             };

NodeChild is in NodeNumber1 once, so I want it as an object and not as a list. Even var1 and var2 are defined once in NodeChild - but they are not problematic because I use FirstOrDefault ).

How I will create it as a single object and not as a list?

var axe = elem.Descendants("NodeNumber1")
               .Select(n => new
               {
                   Name= n.Attribute("Name").Value,
                   MyObj= from o in n.Descendants("NodeChild")
                          select new
                          {
                              var1= o.Descendants("var1").FirstOrDefault().Value,
                              var2= o.Descendants("var2").FirstOrDefault().Value,
                          }
               })
               .First();

Or using existing query:

var axe = axesList.First();

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