Search code examples
c#xmlxelement

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?


Solution

  • 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();