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?

3
  • 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.) Commented Mar 13, 2013 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. Commented Mar 13, 2013 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. Commented Mar 13, 2013 at 14:12

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Your suggestion worked, I edited your answer because I wanted that inner list will be single object and not the external list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.