JG Vimalan's Blog

It is all about coding!

XmlSerialization

The following code snippet will show you how to perform xmlserialization.

The main objective is to read / write data to an xml file using XmlSerialization.

1. Create a Windows application (name as DemoXMLSerialization)
2. Rename the default form as App
3. Add a class MyXmlSerialization and include the code as shown below,
4. Call the MyXmlSerialization APIs from the App class.

Comment is given in the code for easy understanding.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace DemoXMLSerialization
{
    /// <summary>
    /// This class performs xml serialization and de serialization
    /// </summary>
    [XmlRoot(“Demo”)]
    [Serializable]
    public class MyXmlSerialization
    {       
        public MyEmployee Employee = null;
        private static MyXmlSerialization _MyXmlSerialization = null;       
        private static string _FilePath = @”C:\\EmployeeDetails.xml”;

        /// <summary>
        /// Constructor
        /// </summary>
        protected MyXmlSerialization()
        {
            Employee = new MyEmployee();
            Employee.Name = “Test”;
            Employee.Age = 28;
            _MyXmlSerialization = this;
        }

        /// <summary>
        /// Employee details are de serialized from xml file.
        /// </summary>
        /// <param name=”type”></param>
        /// <returns></returns>
        public static MyXmlSerialization Load(Type type)
        {
            XmlSerializer xmlSerializer = null;
            FileStream fileStream = null;

            try
            {
                FileInfo file = new FileInfo(_FilePath);
                if (file.Exists)
                {
                    xmlSerializer = new XmlSerializer(type);
                    fileStream = file.OpenRead();
                    return xmlSerializer.Deserialize(fileStream) as MyXmlSerialization;
                }
                return null;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
        }

        /// <summary>
        /// Save the employee details to the xml file
        /// </summary>
        public void Save()
        {
            XmlSerializer xmlSerializer = null;
            StreamWriter streamWriter = null;

            try
            {
                xmlSerializer = new XmlSerializer(GetType());
                streamWriter = new StreamWriter(_FilePath, false);
                xmlSerializer.Serialize(streamWriter, this);
            }
            catch(Exception error)
            {
                throw error;
            }
            finally
            {
                if (streamWriter != null)
                    streamWriter.Close();
            }
        }

        /// <summary>
        /// Gets the instance of this class.
        /// Used to read/write the values.
        /// </summary>
        public static MyXmlSerialization Options
        {
            get
            {
                if (_MyXmlSerialization == null &&
                    (_MyXmlSerialization = Load(typeof(MyXmlSerialization))) == null &&
                    (_MyXmlSerialization = new MyXmlSerialization()) == null)
                return null;

                return _MyXmlSerialization;
            }
        }

        /// <summary>
        /// Employee class
        /// </summary>
        [Serializable]
        public class MyEmployee
        {
            /// <summary>
            /// Name of the employee
            /// </summary>
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    _Name = value;
                }
            }
            private string _Name = string.Empty;

            /// <summary>
            /// Age of the employee
            /// </summary>
            public int Age
            {
                get
                {
                    return _Age;
                }
                set
                {
                    _Age = value;
                }               
            }
            private int _Age = 0;
        }       
    }
}

 This form will have two buttons namely, serialize and de serialize.

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DemoXMLSerialization
{   
    public partial class App : Form
    {
        public App()
        {
            InitializeComponent();
        }

        private void _SerializeBtn_Click(object sender, EventArgs e)
        {
            //Write to a xml file
            MyXmlSerialization.Options.Save();
        }

        private void _DeSerializeBtn_Click(object sender, EventArgs e)
        {
            //Read from the xml file
            string employeeName = MyXmlSerialization.Options.Employee.Name;
        }
    }
}

 The output xml file will be as shown below,

 xmlSer

Advertisements

September 30, 2009 - Posted by | C#.NET

1 Comment »

  1. thanks bro!

    Comment by kk wells | February 7, 2011 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: