New Favourite Toy - Xml Serialization for generating Xml Feeds (English)

New Favourite Toy - Xml Serialization for generating Xml Feeds

Friday, 12 March 2004

//

1 minute read

I've previously used Xml Serialization for loading and saving config files into and out of apps - nice use...What I've done recently though has been very useful - for me at least. Essentially, I have an application which has a little Poll control, now in ASP.NET this is constructed by binding a collection of items (OptionItem or ResultItem depending on the 'mode')...which are in themselves contained in a VoteItem class to certain controls in the page and to a repeater for displaying the options. Now, a project came in recently which wants to use the functionality of the Poll from ASP - what I decided to do was provide it in the form of an XML feed which the ASP could transform using XSLT into the presentation front-end. What I had planned to do was manually construct the XML string based on the VoteItem class...but then I remembered XMLSerialization - basically one step and I had an XML representation of the vote item - yay! Anyway, I'll modify the code in the next couple of days and upoad a version of the poll to this site (I may even have a poll on here :-)). For the moment, here's a snippet of code which will generate an XML string given a class (any class pretty much...just used it for votes in mine...)

  public string SerializeVote(VoteItem theVote)
  {
   XmlSerializer xSer = new XmlSerializer(typeof(VoteItem));
   MemoryStream writer = new MemoryStream();
   xSer.Serialize(writer,theVote);
   string outStr =  System.Text.ASCIIEncoding.ASCII.GetString(writer.ToArray());
   writer.Close();
   return outStr;

  }

UPDATE: This is a prettry good article on Xml Serialization...

logo

© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.