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?
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With