Basic XML Serialization in C#

Files and Directories

Serialization is the process of converting the state of an object into a sequence of bits so that it can be transferred over a network or saved to a file on disk. With XML Serialization, instead of converting an object’s state to bits, it will convert an object’s state to XML. This is particularly useful for saving and loading application configurations for example.

In this short article we will be creating an employee class and saving an instance of the employee class to an xml file on disk through XML serialization. We will then attempt to load back the employee object from the XML file we created though XML deserialization.

So first let’s create a class called Employee. We are going to add five properties to our Employee class – Name, Surname, DateOfBirth, Sex, and Position. Obviously, an actual employee class would have much more properties such as addresses, contact details, social security number, id number, etc, but for the purpose of this example five properties are more than enough.

Below is what our basic Employee class looks like:

using System;

namespace XMLSerialization
{
    public class Employee
    {
        public enum EmployeeSex
        {
            Male,
            Female
        }

        // Private Members
        private string name;
        private string surname;
        private DateTime dob;
        private EmployeeSex sex;
        private string position;

        // Public Properties
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Surname
        {
            get { return surname; }
            set { surname = value; }
        }

        public DateTime DateOfBirth
        {
            get { return dob; }
            set { dob = value; }
        }

        public EmployeeSex Sex
        {
            get { return sex; }
            set { sex = value; }
        }

        public string Position
        {
            get { return position; }
            set { position = value; }
        }

        // Constructor
        public Employee()
        {
        }
    }
}

As you can see from the above code, I used public properties to access the class private members instead of just making the members themselves public. It is true that it would have been easier to make the members public but I would not advise that since it is not the recommended way of accessing class variables. In our case it would not have made much difference if we opted for public class members, but with larger classes you might want to control what properties can be changed from outside your class, or maybe you would want to validate any values being assigned to your class variables. Anyway, let’s get back on topic…

Now that our Employee class is ready, we want to create an instance of it and serialize that instance. The .NET Framework provides an System.Xml.Serialization.XmlSerializer class which makes life easy for us to serialize our object, but before we can write our serialization code we need to add the following namespaces to our project because our code will be needing them:

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

Now we can create a serialization method which looks like the following:

private void Serialize()
{
    // Create an instance of the Employee class
    Employee employee = new Employee();
    employee.Name = "John";
    employee.Surname = "Smith";
    employee.DateOfBirth = new DateTime(1980, 10, 08);
    employee.Sex = Employee.EmployeeSex.Male;
    employee.Position = "Software Engineer";

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employee.GetType());

    // Create an instance of System.IO.TextWriter 
    // to save the serialized object to disk
    TextWriter textWriter = new StreamWriter("C:\\Employee\\employee.xml");

    // Serialize the employee object
    serializer.Serialize(textWriter, employee);

    // Close the TextWriter
    textWriter.Close();
}

What we are doing in the above code is first we are creating an instance of the Employee class we created earlier, and we are populating values for the employee instance, then we are creating an XmlSerializer object which will do the serialization for us. The XmlSerializer needs to know the type of object we want to serialize so we are passing employee.GetType() as a paramater to give it this information. Then we are creating an instance of System.IO.TextWriter which will be used by the XmlSerializer to create an XML file on disk, and finally we are calling the Serialize() method of the XmlSerializer to create the file and then we are closing the TextWriter.

If you open the file created by the XmlSerializer you should have something like this:

<?xml version="1.0" encoding="utf-8"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>John</Name>
  <Surname>Smith</Surname>
  <DateOfBirth>1980-10-08T00:00:00</DateOfBirth>
  <Sex>Male</Sex>
  <Position>Software Engineer</Position>
</Employee>

As you can see all the properties we set earlier for the employee object are now in the XML file. It is that easy!

Now let’s deserialize the XML file to re-create the same employee object from file. The code to do this is below:

private void Deserialize()
{
    // Create an instance of the Employee class
    Employee employee = new Employee();

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employee.GetType());

    // Create an instance of System.IO.TextReader 
    // to load the serialized data from disk
    TextReader textReader = new StreamReader("C:\\Employee\\employee.xml");

    // Assign the deserialized object to the new employee object
    employee = (Employee)serializer.Deserialize(textReader);

    // Close the TextReader
    textReader.Close();
}

The above deserialization code is very similar to the serialization code. The differences are that we are creating an empty Employee instance – we are not setting any properties because they will be populated from the XML file after deserializing it. The other difference is that this time we are using the System.IO.TextReader class instead of the TextWriter class because we need to read from our file and not write to it.

The below screenshot is displaying the Visual Studio Locals window and you can see the employee object after the deserialization process which confirms that the XML file was deserialized correctly.

Deserialization

As you can see, basic XML Serialization and Deserialization is quite easy to implement. There is a lot more that can be done with XML serialization and I will be explaining more of it in future posts.

I hope this article was of help to you. See you soon.

Dave

6 comments… add one
  • Nice post about Basic XML Serialization in C#

  • Derek Link Reply

    Very helpful for a beginner, I found this very easy to understand and implement!
    Thank you!

  • sina Link Reply

    Very helpful but i have a doubt would be great if you could help! How would the c# code be modified so as the serialized xml looks like this:

    John
    Smith

    Thanks in advance!

Leave a Comment