C# Object Persistence with Xml

In today’s post I’d like to share two different ways of using XML Serialization in C#. This is handy if you need to work with small XML files. Take the following class as an example:

[Serializable]
public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
}

Now, add the following two methods to the Person class. Note the use of the static keyword on the load method. This allows us to call the Load method on the Person class without creating an instance of a Person.

public static Person Load(string path)
{
  Person savedPerson = null;
  XmlSerializer x = new XmlSerializer(typeof(Person));
  using (FileStream st = File.Open(path, FileMode.Open))
  {
    savedPerson = (Person)x.Deserialize(st);
  }
  return savedPerson;
}

public void Save(string path)
{
  XmlSerializer x = new XmlSerializer(typeof(Person));
  using (FileStream st = File.Open(path, FileMode.Create))
  {
    x.Serialize(st, this);
  }
}

Using the code above we can serialize an instance of our class like this:

Person p = new Person();
p.FirstName = "Joe";
p.LastName = "Bloggs";
p.Age = 40;
p.Save("joebloggs.xml");

Person joe = Person.Load("joebloggs.xml");

We can take this one step further by using generics. Instead of adding methods to our Person class, we can create a static utility class that does the same job, but is type independent:

public static class XmlSerializerUtil
{
  public static T Load<T>(string path)
  {
    T savedObject = default(T);
    XmlSerializer x = new XmlSerializer(typeof(T));
    using (FileStream st = File.Open(path, FileMode.Open))
    {
      savedObject = (T)x.Deserialize(st);
    }
    return savedObject;
  }

  public static void Save<T>(string path, T obj)
  {
    XmlSerializer x = new XmlSerializer(typeof(T));
    using (FileStream st = File.Open(path, FileMode.Create))
    {
      x.Serialize(st, obj);
    }
  }
}

We can now serialize an instance of our class like this:

Person p = new Person();
p.FirstName = "Joe";
p.LastName = "Bloggs";
p.Age = 40;

XmlSerializerUtil.Save<Person>("joebloggs.xml", p);
Person p = XmlSerializerUtil.Load<Person>("joebloggs.xml");

Since we’re using Generics, we’re specifying the type when we invoke the method, rather than inside the static utility class. This allows us to serialize different object types using the same code.

Advertisements
This entry was posted in Reference and tagged , . Bookmark the permalink.

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