Serializing Data with System.Xml.Serialization.XmlSerializer

Serializing objects is often a useful way to save the state of an application. Let’s take a look at doing this using the XmlSerializer object.

Class: Person

Below is a simple class Person. My person has a name and an age:

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person() {
    }
}

The XmlSerializer requires that I leave an empty constructor in my class. I can make the constructor private if I don’t want it used for other things. Now, let’s create an instance of a Person.

class Program {
    static void Main(string[] args) {
        Person myPerson = new Person();
        myPerson.FirstName = "John";
        myPerson.LastName = "Smith";
    }
}

How to serialize our class

I will add a couple methods now to handle serializating and deserializing myPerson.

static void XmlSerializePerson(Person myPerson, string fileName) {
    XmlSerializer xs = new XmlSerializer(typeof(Person));

    using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) {
        xs.Serialize(fs, myPerson);
    }
}

static Person XmlDeserializePerson(string fileName) {
    XmlSerializer xs = new XmlSerializer(typeof(Person));

    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
        return (Person)xs.Deserialize(fs);
    }
}

Code in action

Now, saving myPerson is simple:

static void Main(string[] args) {
    Person myPerson = new Person();
    myPerson.FirstName = "John";
    myPerson.LastName = "Smith";

    XmlSerializePerson(myPerson, @"C:\MyPerson.xml");
}

Let’s take a look at the resulting XML:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>John</FirstName>
  <LastName>Smith</LastName>
</Person>

Now, let’s deserialize our person and display its data:

static void Main(string[] args) {
    Person myPerson = XmlDeserializePerson(@"C:\MyPerson.xml");

    Console.WriteLine("Name: " + myPerson.LastName + ", " + myPerson.FirstName);
    Console.ReadLine();
}

The result:

image

As you can see, the XmlSerializer did its job.

Download the Solution

You can download a zip file of the solution by clicking the link below.

XmlSerializerDemo.zip

Leave a Reply