Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 351
user2067567 Avatar asked Apr 30 '13 10:04

user2067567


2 Answers

I see that you have accepted an answer. But I just want to show another way which I like. First you will need classes as 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 it will be helpful.

like image 96
Adil Mammadov Avatar answered Sep 27 '22 22:09

Adil Mammadov


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();
like image 42
Anirudha Avatar answered Sep 28 '22 00:09

Anirudha