Converting a XML to Generic List

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

I am trying to convert XML to List


  
    2
    dummy
    
12
相关标签:
3条回答
  • 2020-12-10 13:14

    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();
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2020-12-10 13:19
    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 class call Student with id, name and section as properties and do:

    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();
    
    0 讨论(0)
提交回复
热议问题