.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Converting XML data to CLR object using XmlSerializer

Posted By:Manas Patnaik       Posted Date: February 14, 2011    Points: 75    Category: Silverlight    URL: http://www.dotnetspark.com  

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.

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 had concluded there ,this post is the continuation of previous .Here i am going to demonstrate How to convert the result output , which is in XML, to CLR object and of course using it as datasource in SL app.

Source Code and Links

GeoSearch Live Link - : GeoSearch

Download SourceCode -: GeoSearch

GeoSearch , the example Project

GeoName is 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 have geo 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 at SL project using either of the method mentioned bellow

  • Using XmlReader
  • Using XLINQ
  • Using XmlSerializer

As XMlReader and XLINQ are quite straight forward so I am going to skip it for the time being ,but still you can have a look into those topics with this links(Parsing XML with Xlinq,XmlReader).This post describes how to deserialize the XML file to collection of CLR object using XMLSerializer class and attributes .

Little bit about System.Xml.Serialization

This namespace contains classes and attributes that allows us to convert a object to xml and vise versa.Attributes can be defined against CLR object  members for serialize and deserialize .This MSDN resource will give you a detailed insight about the namespace.As this post is concerned about converting the XML to CLR objects ,lets focus on it.

Project GeoSearch

For converting XML to objects basically involves 3 steps

  1. Create the Schema /class from XML
  2. Apply Attributes to the members of the generated class
  3. Using XMLSerializer class deserialize it
1. Create the Schema /class from XML

Using VS2010 create a XML schema over the XML result file. image

To generate the class structure from schema i am going to use XSD2CODE tool available at codeplex (http://xsd2code.codeplex.com/). Once installed select your generated schema file in solution explorer and run code generator.


This way you will be able to generate the skeleton of classes and members based on supplied XML schema .But as we dont want our class/property name to be same as generated by the tool lets change it .By modifying some embers name of the generated classes ,the output (by default the names will be based on the Tag and element names of XML) will be as bellow .

  1. namespace GeoSearch
  2. {
  3. ///
  4. /// Class For geonames
  5. /// class containing the collection of location
  6. ///
  7. public partial class Location
  8. {
  9. public ushort totalResultsCount { get; set; }
  10. public List<GeoDetail> GeoDetails { get; set; }
  11. public string style { get; set; }
  12. }
  13. ///
  14. /// Class For geoname
  15. /// Details about each location
  16. ///
  17. public class GeoDetail
  18. {
  19. public string toponymName { get; set; }
  20. public string name { get; set; }
  21. public decimal lat { get; set; }
  22. public decimal lng { get; set; }
  23. public uint geonameId { get; set; }
  24. public string countryCode { get; set; }
  25. public string countryName { get; set; }
  26. public string fcl { get; set; }
  27. public string fcode { get; set; }
  28. }
  29. }
2. Apply Attributes to the members of the generated class

As you can notice ,i have changed the class name of both generated class.By doing so i have to add some attribute to the class so that it can relate it self to the XML .Lets compare the XML and the class side by side and map the element to the class.


The XMLRoot attribute direct the deserialization process saying that "Location" targets "geonames" root of the XML.Similarly for GeoDetail class.Now have a look at Location class.Structuring the class as per the XML the Location is going to have a collection of GeoDetail (geoname in the XML), and having a attribute of XMLElement specifying the name of the element name in xml.One point should be kept in mind if the class and its members carries same name as XML root and element then  there is no need of adding extra attribute .

More detailed attribute uses on casebased scenario can be found here with MSDN Link.

3. Using XMLserlizer class deserialize it
  1. string baseServiceURL = @"http://api.geonames.org/search?q={0}&username=demo";
  2. public MainPage()
  3. {
  4. InitializeComponent();
  5. }
  6. private void btnCallService_Click(object sender, RoutedEventArgs e)
  7. {
  8. //Check For Empty Text value
  9. if (String.IsNullOrWhiteSpace(txtPlace.Text))
  10. {
  11. MessageBox.Show("Provide a location name for result");
  12. return;
  13. }
  14. WebClient client = new WebClient();
  15. //Apply Callback
  16. client.OpenReadCompleted += (s, ev) =>
  17. {
  18. XmlSerializer serializer = new XmlSerializer(typeof(Location));
  19. try
  20. {
  21. Stream stream = ev.Result;
  22. Location Loc = (Location)serializer.Deserialize(stream);
  23. lstSearchResult.ItemsSource = Loc.GeoDetails;
  24. lblNoOfRows.Content=string.Format("About {0} results ",Loc.totalResultsCount.ToString());
  25. }
  26. catch (Exception exp)
  27. {
  28. MessageBox.Show(exp.InnerException.Message);
  29. }
  30. finally
  31. {
  32. biSearch.IsBusy = false;
  33. }
  34. };
  35. string serUrl = String.Format(baseServiceURL, txtPlace.Text);
  36. biSearch.IsBusy = true;
  37. client.OpenReadAsync(new Uri(serUrl));
  38. }
  39. }

For sending and receiving data on web , Silverlight exposes classes WebClient and HTTpWebrequest.Both uses basic GET and POST based verbs for retrieval and invocation.As compared to HTTPWebRequest , webclient is quite simple and straight forward and supports event based call-back.However HttpRequest is more suitable for advanced REST service call allowing more control over HTTP request.

The XmlSerializer class ,System.Xml.Serialization namespace ,methods responsible for converting a plain XML to a objects .In this example we are creating a instance of XmlSerlizer with Location type as constructor saying the type of object its going to operate is of Location.


Once the OpenReadAsync operation completes the results are taken into a stream and passed to Deserialize methods for conversion.

Assign Datasource and Lets run .

The code above is ready to return a collection of GeoDetail which we have assigned to the list box with a defined DataTemplete.The itemtemplete for list box is quite simple with xaml based declarative binding expression.


Hooo.. ,Now its ready to go Live , Check a working demo with link bellow.


The strongly typed XML with objects and serialization gives application the power of transportability although it comes with bit of extra effort at initial stage of development.Still there is lot more to be rediscover and more complex XML format can be handled  .That's all for this time , Keep Learning , i will brbBe right back.

Source Code and Links

GeoSearch Live Link - : GeoSearch

Download SourceCode -: GeoSearch

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend