Search...

Sunday, February 26, 2012

Serialize & De-serialize your business objects to XML

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace SerializeToXML
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie movie = new Movie();
            movie.Title = "Ghost Rider 2";
            movie.ReleaseDate = DateTime.Parse("24/Feb/2012");
            movie.Rating = 4.2f;

            List<Movie> list = new List<Movie>() { movie};
            movie.SerializeToXML(list);
            var data =movie.DeserializeFromXML();
            foreach(var x in data)
            {
                Console.WriteLine(x.Title+" "+x.Rating+" "+x.ReleaseDate);
            }
            Console.ReadLine();
        }
    }

    public class Movie
    {
        [XmlAttribute("MovieName")]
        public string Title{ get; set; }
        [XmlElement("MovieRating")]
        public float Rating{ get; set; }
        [XmlElement("MovieReleaseDate")]
        public DateTime ReleaseDate{ get; set; }

        public void SerializeToXML(List<Movie> movies)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Movie>));
            TextWriter textWriter = new StreamWriter(@"d:\movie.xml");
            serializer.Serialize(textWriter, movies);
            textWriter.Close();
        }

        public List<Movie> DeserializeFromXML()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
            TextReader textReader = new StreamReader(@"d:\movie.xml");
            List<Movie> movies;
            movies = (List<Movie>)deserializer.Deserialize(textReader);
            textReader.Close();
            return movies;
        }
    }
}

No comments: