0

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?

default
  • 11,485
  • 9
  • 66
  • 102
Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111
  • Well you've got two "levels" of output here - one with Name/MyObj, and one with var1/var2. Which do you want to make singular? (Sample XML and expected output would be useful.) – Jon Skeet Mar 13 '13 at 13:51
  • I get the name - is already singular, and MyObj as a list which has the Var1/Var2, I want this list will become a single object. – Hodaya Shalom Mar 13 '13 at 13:53
  • So you want `myList` to still be a list? Can you see how your question is confusing, and could have been much more clearly described, with sample XML and expected output? Please bear this in mind for next time. – Jon Skeet Mar 13 '13 at 14:12

1 Answers1

1
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();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Your suggestion worked, I edited your answer because I wanted that inner list will be single object and not the external list – Hodaya Shalom Mar 13 '13 at 14:01