Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting several node values using LINQ

Tags:

c#

.net

linq

So lets say you have the following XML-structure.

 <Class>
  <Students>
    <Student>
      <StudentNo>555</StudentNo>
      <Firstname>Joe</Firstname>
      <Lastname>Smith</Lastname>
    </Student>
     <Student>
      <StudentNo>222</StudentNo>
      <Firstname>Smith</Firstname>
      <Lastname>Joe</Lastname>
    </Student>
  <Students>
</Class>

And you would like to get all the Firstnames and lastnames using linq. For now I got the following

foreach (XElement x in data.Descendants("Student").SelectMany(e => data.Descendants("Firstname")))
            {
                Console.WriteLine(x.Value);
            }

But how could i get lastName as well?

like image 646
Ørjan Avatar asked Mar 18 '26 01:03

Ørjan


1 Answers

You can do this using an anonymous type:

var query=data.Descendants("Student")
              .Select(s=> new { FirstName=s.Element("FirstName").Value,
                                LastName=s.Element("Lastname").Value});

Or you can create a custom class and save the result:

var query=data.Descendants("Student")
              .Select(s=> new Student{ FirstName=s.Element("FirstName").Value,
                                       LastName=s.Element("Lastname").Value});
like image 131
octavioccl Avatar answered Mar 20 '26 14:03

octavioccl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!