Deserialize the XML response to a Data class
This article explains how to deserialize an XML response to a Data class
In a previous article I explained the steps to create a data class for an XML response.
This data class will be used to de serialize (parse & fill the values of properties) an XML response.
Below is the code showing how to parse & fill the values of properties in an XML response.
//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 the response of your web request. We are creating a memory stream from this response string.
Initialize the new instance of XmlSerializer. Its constructor accepts the Type to be de-serialized to - in this case your data class.
//Deserialize memory stream.
students sd = (students) serializer.Deserialize(ms);
Deserialize the XML document (memory stream) into an object of the specified type using an instance of XmlSerializer.
Thus, We will have our 'sd' object with properties filled with the values from the XML document (response) of our web request to get the list of students.
sd has an array (Items) which has instances of the studentsStudent class. The studentsStudent class contains the details for the student. Property names of the class are same as elements in XML response. This is another class also created in the file Students.cs by the xsd tool.
We can use this 'sd' object (and hence its array) to populate a list box (or other related control) in our UI.
This is the simplest way to de-serialize an XML documents to a class object.