如何在C#中对xml对象进行反序列化

How to Desiralize xml object in C#


问题

大家好,

我需要将下面的xml对象反序列化为下面各自的模型,如何做到这一点。请建议我

xml对象
<RESPONSE>
<SchoolList>
<School>
<SchoolID> 102</SchoolID>
< SchoolName>ABC</SchoolName>
<StudentList>
<Student>
<StudentName>JOHN</StudentName>
< ClassName>IX</ClassName>
<Age>13</Age>
</Student>
<Student>
<StudentName> Taylor< /StudentName>
<ClassName>IIX</ClassName>
<Age>11</Age>
</Student>
</StudentList>
< /School>
<School>
<SchoolID>103</SchoolID>
<SchoolName>BCD</SchoolName>
<StudentList>
<Student>
<StudentName>CHRIS</StudentName>
<ClassName>IV</ClassName>
<Age> 9</Age>
</Student>
</StudentList>
</School>
</SchoolList>
</RESPONSE>
Models
public class School
{
public List< Student> StudentList;
public int SchoolID { get; set; }
public string SchoolName { get; set; }
}
public class Student
{
public string StudentName { get; set; }
public string ClassName { get; set; }
public int ? 年龄 { get; set; }
}

谢谢,
King



你说的 "xml对象 "是指像 XmlDocument XDocument 这样的对象吗?


答案1

你需要一个额外的类:

 public class RESPONSE
 {
     public List<School> SchoolList;
 } 

然后你可以使用XmlSerializer类来反序列化这个xml。

             string xmlString = File.ReadAllText(@"C:\...\2.xml");
             XmlSerializer xmlSerializer = new XmlSerializer(typeof(RESPONSE));
             using (TextReader reader = new StringReader(xmlString))
             {
                 RESPONSE result = (RESPONSE)xmlSerializer.Deserialize(reader);
    
             }


我可以知道你的问题是否已经解决了吗?如果没有,请在这里分享。我们可以一起工作来解决这个问题。

相同问题还可以参考: How to Desiralize xml object in C#