Tuesday, February 15, 2011

Converting XML data to CLR object using XmlSerializer

My last Post (Consuming Webservice from Silverlight) was all about accessing a web service/API from Silverlight; there I described how to consume an external API, with a sample from GeoName web services. As I said in that article, this article is the continuation. Here I am going to demonstrate how to convert the result output, which is in XML, to a CLR object and of course using it as a datasource in a Silverlight application.

GeoSearch, the example Project

GeoName is a provider of various web service/API exposing information about geographic details of places.You can visit their website here. So using their service I am going to design a search page where the user can retrieve geographical details based on name.

On accessing the serviceurl (http://api.geonames.org/search?q=orissa&username=demo) it returns set of data as XML format. Lets have a look into the XML file. You can try the same service URL at your browser and can check the xml file.

As in my last post I had mentioned this result XML can be parsed by a Silverlight application using either of the methods mentioned below:

Using XmlReader
Using XLINQ
Using XmlSerializer

Since XMlReader and XLINQ are quite straight forward, I will skip them for the time being, but still you can have a look into those topics with these links (Parsing XML with Xlinq,XmlReader). This article describes how to deserialize the XML file to a collection of CLR objects using XMLSerializer class and attributes.

Little bit about System.Xml.Serialization

This namespace contains classes and attributes that allows us to convert an object to XML and vise versa. Attributes can be defined against CLR object members for serialization and deserialization. This MSDN resource will give you a detailed insight into the namespace. Since this article is concerned about converting the XML to CLR objects, let's focus on it.

Project GeoSearch

Converting XML to objects basically involves 3 steps
Create the Schema /class from XML
Apply Attributes to the members of the generated class
Using XMLSerializer class deserialize it
1. Create the Schema /class from XML
Use VS2010 to create a XML schema over the XML result file.

Read more: C# Corner