Convert XML to a general 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 have tried several things using LINQ, and I do not really understand what is going on.

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

Gets counter 2, but values โ€‹โ€‹as 2dummy12 3dummy11

Is it possible to convert the above XML into a generic list of type Student that has the properties Id, Name and Section?

How can I implement this?

+8
c # xml-parsing linq
source share
3 answers

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(); 

Creates a list of anonymous type.


If you want to create a list of type Student

 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(); 
+11
source share

I see that you accepted the answer. But I just want to show another way that I like. First you will need classes as shown below:

 public class Student { [XmlElement("Id")] public int StudentID { get; set; } [XmlElement("Name")] public string StudentName { get; set; } [XmlElement("Section")] public int Section { get; set; } } [XmlRoot("School")] public class School { [XmlElement("Student", typeof(Student))] public List<Student> StudentList { get; set; } } 

Then you can deserialize this xml:

 string path = //path to xml file using (StreamReader reader = new StreamReader(path)) { XmlSerializer serializer = new XmlSerializer(typeof(School)); School school = (School)serializer.Deserialize(reader); } 

Hope this will be helpful.

+12
source share
 var students = from student in dox.Descendants("Student") select new { id=d.Element("Id").Value, Name=d.Element("Name").Value, Section=d.Element("Section").Value }).ToList(); 

or you can create a call to the Student class with the identifier, name and section as properties and follow these steps:

 var students = from student in dox.Descendants("Student") select new Student { id=d.Element("Id").Value, Name=d.Element("Name").Value, Section=d.Element("Section").Value }).ToList(); 
+1
source share

All Articles