Thursday, November 5, 2009

.NET - Serialization to XML and back - Saving/reading custom configuration files

XML serialization in the .net framework is a powerful and very useful technology, yet I wasn't too familiar with it, so I felt I should blog about it. One of the situation where I think it is very appropriate to use this is to create custom configurations and read/save/modify them for web (server) or desktop applications. Using the asp.net Cache class it is also possible to assign the serialized file as a cache dependency thereby re-read and re-hydrate the serialized object from the xml file. This is a perfect scenario for xml configuration files. The below links are references and the code is from "switch on the code c# xml serialization tutorial", link shown below.
STEP 1: Create a simple .net class (Plain old .NET object, PONO), for example:

public class Movie
{
  public string Name
  { get; set; }

  public int Rating
  { get; set; }

  public DateTime ReleaseDate
  { get; set; }
}


STEP 2: Serialize it to Xml using the XmlSerializer class:


static public void SerializeToXML(Movie movie)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Movie));
  TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
  serializer.Serialize(textWriter, movie);
  textWriter.Close();
}

It would produce an XML file, named movie.xml, as:
<?xml version="1.0" encoding="utf-8"?>
<Movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Starship Troopers</Title>
  <Rating>6.9</Rating>
  <ReleaseDate>1997-11-07T00:00:00</ReleaseDate>
</Movie>




STEP 3: Modify the Xml file and deserialize (update and re-hydrate) the .net object from the xml file:

static Movie DeserializeFromXML()
{
   XmlSerializer deserializer = new XmlSerializer(typeof(Movie));
   TextReader textReader = new StreamReader(@"C:\movie.xml");
   Movie movie = (Movie)deserializer.Deserialize(textReader);
   textReader.Close();

   return movie;
}


1 comment:

  1. Flex Developer in India- Get the cheap and best flex developer, flex designer, flex application developer, flex application development, flex application design and much more at flexdeveloper.in. We also outsource flex work to freelancers.

    ReplyDelete