user2067567 user2067567 - 2 months ago 13
C# Question

Converting a XML to Generic List

I am trying to convert XML to List

<School>
<Student>
<Id>2</Id>
<Name>dummy</Name>
<Section>12</Section>
</Student>
<Student>
<Id>3</Id>
<Name>dummy</Name>
<Section>11</Section>
</Student>
</School>


I tried few things using LINQ and am not so clear on proceeding.

dox.Descendants("Student").Select(d=>d.Value).ToList();


Am getting count 2 but values are like
2dummy12 3dummy11


Is it possible to convert the above XML to a generic List of type Student which has Id,Name and Section Properties ?

What is the best way I can implement this ?

Answer

You can create an anonymous type

var studentLst=dox.Descendants("Student").Select(d=>
new{
    id=d.Element("Id").Value,
    Name=d.Element("Name").Value,
    Section=d.Element("Section").Value
   }).ToList();

This creates a list of anonymous type..


If you want to create a list of Student type

class Student{public int id;public string name,string section}

List<Student> studentLst=dox.Descendants("Student").Select(d=>
new Student{
    id=d.Element("Id").Value,
    name=d.Element("Name").Value,
    section=d.Element("Section").Value
   }).ToList();
Comments