XML serialization in C#

XML serialization in C# is not a complex subject, but somehow, every time I have to implement it inside a project, I find small issues I have to solve in order for the process to work without problems. So, here is it how it works…

Step 1: I first start by implementing an XmlHelper class, that I can use in any project, without references to any specific objects:

using System;
using System.Xml.Serialization;
using System.IO;

namespace XmlSerializationSample
{
    public class XmlHelper
    {
        public static void Serialize(String fileName, Object obj, Type objType)
        {
            XmlSerializer serializer = new XmlSerializer(objType);
            using (TextWriter textWriter = new StreamWriter(fileName))
            {
                serializer.Serialize(textWriter, obj);
                textWriter.Close();
            }
        }

        public static object Deserialize(String fileName, Type objType)
        {
            Object obj = null;
            XmlSerializer serializer = new XmlSerializer(objType);
            using (TextReader textReader = new StreamReader(fileName))
            {
                obj = serializer.Deserialize(textReader);
                textReader.Close();
            }
            return obj;
        }
    }
}

As you can see, things are pretty straight-forward: the Serialize method takes a given object, its type, and serializes it to a file specified through fileName parameter. The same way, Deserialize method receives the object type and the file name where the object is “XML-serialized”, returning an object with the desired structure. Of course, a cast will be needed inside the class where the method is used. Both method are static, we don’t need any instances of the parent class.

Step 2: Define the objects that will be serialized:

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

namespace XmlSerializationSample
{
    [XmlRoot("ReplaceRules")]
    public class ReplaceRules
    {
        private ArrayList replaceRules = new ArrayList();

        [XmlElement("ReplaceRule")]
        public ReplaceRule[] Rules
        {
            get
            {
                ReplaceRule[] rules = new ReplaceRule[replaceRules.Count];
                replaceRules.CopyTo(rules);
                return rules;
            }
            set
            {
                if (value == null) return;
                ReplaceRule[] rules = (ReplaceRule[])value;
                replaceRules.Clear();
                foreach (ReplaceRule rule in rules)
                    replaceRules.Add(rule);
            }
        }

        public int AddRule(ReplaceRule rule)
        {
            return replaceRules.Add(rule);
        }
    }

    public class ReplaceRule
    {
        [XmlAttribute("Word")]
        public string Word { get; set; }

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

        public ReplaceRule()
            : this(string.Empty, string.Empty)
        {
        }

        public ReplaceRule(string word, string replacement)
        {
            this.Word = word;
            this.Replacement = replacement;
        }
    }
}

In order to control the serialization process, one will use attributes like XmlRoot, XmlElement and XmlAttribute. One important notice should be taken to account: only public fields will be serialized to XML.

Step 3: Use the methods to serialize given objects:

ReplaceRules rules = new ReplaceRules();
rules.AddRule(new ReplaceRule("public", "seen by anyone"));
rules.AddRule(new ReplaceRule("protected", "seen inside descendants"));
rules.AddRule(new ReplaceRule("private", "seen inside current item"));
XmlHelper.Serialize("C:\Output.xml", rules, typeof(ReplaceRules));
ReplaceRules secondRules = (ReplaceRules)XmlHelper.Deserialize("C:\Output.xml", typeof(ReplaceRules));

Step 4: Check the output :).

01XmlSerializationCSharpPreview

Advertisements

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: