Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

c# - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...