Deserialize the XML response to a Data class
This article explains how to deserialize the XML response to a Data class
In previous article I explained the steps to create data class for the XML response.
This data class will be used to de-serialize (parse & fill the values for variables) the XML response.
Below is the code which shows how to do this....
//Get the Memory Stream from the response string.
Byte memBytes = Encoding.UTF8.GetBytes(xmlResponseString);
MemoryStream ms = new MemoryStream(memBytes);
Here, 'xmlResponseString' is the string containing response of your web request. We are creating a memory stream from this response string.
//Create the XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(students));
Initialize the new instance of XmlSerializer. Its constructor accepts the Type, provide the type of our data class.
//De-Serialize memory stream.
students sd = (students) serializer.Deserialize(ms);
Deserialize the XML document (memory stream) into object of specified type while creating instance of XmlSerializer.
Thus, We will have our 'sd' object with variables filled with values in XML document (response) for our web request to get list of students.
sd has an array (Items) which has instances of 'studentsStudent' class. studentsStudent class contains the details for the student. Variable's name of the class are same as elements in XML response. This another class is also created in file "Students.cs" by xsd tool itself.
We can use this 'sd' object (and hence its array) to populate the list box (or other related control) in our UI.
This is the simplest way to deserialize the XML documents to a class object.