Serialize and Deserialize objects into files using the System.Xml.Serialization in C# .NET

Tuesday, 19 May 2009 10:33 by myro

Serialization in C# and in .NET is really simple if just need to convert simple objects and collections in XML format. This article will show you the basic steps to serialize and deserialize objects into a xml file. Keep in mind that are different ways to accomplish this task, and you are always allowed to create you own serialization pattern implementing the ISerializable interface into your objects and collection. This time i will only cover the simple way by creating a colloection of my object that i want to serialize, a static manager (to simplify the serialization / deserialization process) and a simple console application to display you the result. 
Imagine you need to save or load a specific configuration file for your application at runtime… would it be nice to create a simple XML file which allows to edit it?  Here’s the deal:

First of all you need to create an object that you need to serialize:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Collections;

namespace SampleSerailizer
{
    [Serializable]
    public class Configuration
    {
        public Configuration()
        {

        }

        [XmlAttribute("Name")]
        public string Name { get; set; }

        [XmlAttribute("ID")]
        public int ID { get; set; }

        [XmlElement("Values")]
        public string[] Values { get; set; }

    }
}

You can see how is easy to determine which properties needs to be serialized: just add the proper decoration attribute to your properties. You can use theXmlIgnore decoration

[XmlIgnore]

if you want to skip this process for a specific property.

Now we need a class that will care to do this job. I have created a static class named ConfigurationManager and created 2 static methods that allows me to save or to load my objects:

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

namespace SampleSerailizer
{
     public static class ConfigurationManager
    {
         public static List<Configuration> LoadConfiguration(string path)
         {
             List<Configuration> toReturn;
             XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>));
             TextReader reader = new StreamReader(path);
             toReturn = (List<Configuration>)serializer.Deserialize(reader);
             reader.Close();
             return toReturn;
         }

         public static void SaveConfiguration(List<Configuration> configuration, string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>));
            TextWriter writer = new StreamWriter(path);
            serializer.Serialize(writer, configuration);
            writer.Close();
        }
    }
}

You are done! Let’s create some sample data and try to serialize it into a XML format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SampleSerailizer
{
    class Program
    {
        static void Main(string[] args)
        {
            // lets add some sample configurations
            List<Configuration> list = new List<Configuration>();
            list.Add(new Configuration() {
                ID = 1 ,
                Name = "Application Configuration",
                Values = new string[] { "sample data 1", "sample data 2" }
            });

            list.Add(new Configuration()
            {
                ID = 2,
                Name = "More Configurations",
                Values = new string[] { "sample data 3", "sample data 4" }
            });

            //save the configuration to a xml file
            ConfigurationManager.SaveConfiguration(list, @"sample configuration.xml");

            //load the configuration from a xml file
            List<Configuration> loadedConfiguration =
           ConfigurationManager.LoadConfiguration(@"sample configuration.xml");

            // display the configuration collection
            foreach (var conf in loadedConfiguration)
            {
                Console.WriteLine(String.Concat(conf.ID, ". - ", conf.Name));
                foreach (var str in conf.Values)
                {
                    Console.WriteLine(String.Concat("--- ", str));
                }
                Console.WriteLine();
            }

            Console.ReadLine();

        }
    }
}

The output displayed in the console compared to the sample configuration.xml shows that it works..

Console output:
ConsoleXML sample configuration.xml:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Configuration Name="Application Configuration" ID="1">
    <Values>sample data 1</Values>
    <Values>sample data 2</Values>
  </Configuration>
  <Configuration Name="More Configurations" ID="2">
    <Values>sample data 3</Values>
    <Values>sample data 4</Values>
  </Configuration>
</ArrayOfConfiguration>

This snipped can be used for a quickly reference to this approach. For a deeper explanation, consider visiting the msdn.

Download the source code: SampleSerailizer.rar (23.84 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.