Converting a XML to Generic List

后端 未结 3 641
無奈伤痛
無奈伤痛 2020-12-10 12:35

I am trying to convert XML to List


  
    2
    dummy
    
12
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 13:17

    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 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.

提交回复
热议问题