Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Deserialize the XML response to a Data class

From Wiki
Jump to: navigation, search

This article explains how to deserialize an XML response to a Data class 

WP Metro Icon File.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
CompatibilityArticle
Created: Kavit Patel (25 Apr 2012)
Last edited: hamishwillee (09 Sep 2013)


Introduction

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.

Code snippets

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.

//Create the XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(students));

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.

This page was last modified on 9 September 2013, at 06:20.
311 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×