Generic XML Serializer Class for C# and an XML Serialization usage example

Hey all,

Today I was working on XML Serialization.

After learning how to do it, I discovered it takes four lines of code to write an XML and four lines of code to read in an XML.

However, I prefer one line of code to four so I made a Serializer.cs class with two static functions.

After thinking about it, I made these classes generic so they work with any type. I hope this helps someone.

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

namespace BlogTool
{
    public class Serializer
    {
        #region Functions
        public static void SerializeToXML<t>(T t, String inFilename)
        {
            XmlSerializer serializer = new XmlSerializer(t.GetType());
            TextWriter textWriter = new StreamWriter(inFilename);
            serializer.Serialize(textWriter, t);
            textWriter.Close();
        }

        public static T DeserializeFromXML<t>(String inFilename)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(T));
            TextReader textReader = new StreamReader(inFilename);
            T retVal = (T)deserializer.Deserialize(textReader);
            textReader.Close();
            return retVal;
        }
        #endregion
    }
}

So now if you have a class you can more easily serialize it to and from an XML.

Here is an example Project that contains these files:

  • Blog.cs
  • BlogList.cs
  • Program.cs
  • Serializer.cs

Blog.cs

using System;

namespace BlogTool
{
    [Serializable()]
    public class Blog
    {
        #region Member Variables
        String mBlogUrl;
        String mCategory;
        #endregion

        #region Constructors
        public Blog()
        {
        }

        public Blog(String inURL, String inCategory)
        {
            mBlogUrl = inURL;
            mCategory = inCategory;
        }
        #endregion

        #region Properties
        public String BlogUrl
        {
            get { return mBlogUrl; }
            set { mBlogUrl= value; }
        }

        public String Category
        {
            get { return mCategory; }
            set { mCategory= value; }
        }
        #endregion
    }
}

BlogList.cs

using System.Collections.Generic;

namespace BlogTool
{
    [Serializable]
    public class BlogList
    {
        #region Member Variables
        List<blog> mBlogs = new List<blog>();
        #endregion

        #region Constructors

        /*
		 * The default constructor
 		 */
        public BlogList()
        {
        }

        #endregion

        #region Properties
        public List<blog> Blogs
        {
            get { return mBlogs; }
            set { mBlogs = value; }
        }
        #endregion
    }
}

Program.cs

namespace BlogTool
{
    class Program
    {
        static void Main(string[] args)
        {
            BlogList bloglist = new BlogList();
            Blog b1 = new Blog("http://rhyous.com","Software");
            Blog b2 = new Blog("http://www.alittletipsy.com", "Crafts");
            bloglist.Blogs.Add(b1);
            bloglist.Blogs.Add(b2);
            Serializer.SerializeToXML(bloglist, "FavoriteBlogs.xml");
        }
    }
}

Serializer.cs

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

namespace BlogTool
{
    public class Serializer
    {
        #region Functions
        public static void SerializeToXML<t>(T t, String inFilename)
        {
            XmlSerializer serializer = new XmlSerializer(t.GetType());
            TextWriter textWriter = new StreamWriter(inFilename);
            serializer.Serialize(textWriter, t);
            textWriter.Close();
        }

        public static T DeserializeFromXML<t>(String inFilename)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(T));
            TextReader textReader = new StreamReader(inFilename);
            T retVal = (T)deserializer.Deserialize(textReader);
            textReader.Close();
            return retVal;
        }
        #endregion
    }
}

Ok, so now that you have the files, you can run this program.

In the bin\debug or bin\release directory where you executable is placed when you build, you will see the FavoriteBlogs.xml file. The XML should look as follows:

<?xml version="1.0" encoding="utf-8"?>
<blogList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <blogs>
    <blog>
      <blogUrl>http://rhyous.com</blogUrl>
      <category>Software</category>
    </blog>
    <blog>
      <blogUrl>http://www.alittletipsy.com</blogUrl>
      <category>Crafts</category>
    </blog>
  </blogs>
</blogList>

I know, this is not written very well as a walk-thru, but I wrote it fast. Maybe I will clean it up later.

Sources:
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

2 Comments

  1. Phil Cooper says:

    Wouldn’t this fail since there isn’t a constructor that takes 2 arguments for Blog()?

Leave a Reply