How to Desiralize xml object in C#

chandu king 21 Reputation points
2021-07-08T04:42:08.317+00:00

Hello Everyone,

I need to deserialize below xml object into the respective models below. how to do this. please suggest me

xml object
<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 ? Age { get; set; }
}

Thanks,
King

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2021-07-08T06:15:57.893+00:00

    You need an additional class:

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

    Then you can use XmlSerializer Class to deserialize this 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);  
      
                }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.