Click here to Skip to main content
Click here to Skip to main content

Wrap the .NET Xml Serialization Framework

, 1 Jun 2003
Rate this:
Please Sign up or sign in to vote.
This lightweight base class trivializes Xml Serialization and eliminates duplication in projects with multiple serializable classes.

Introduction

The .NET Framework's XML Serializer allows you to save an object's state to an xml file with a user-defined format. This can be especially useful when importing or exporting data to or from someone else's format. It can also be used as a quick-and-dirty data store or as a simple means of debugging object state.

Whatever your task, once you've written several classes that make use of the Xml Serializer, the coding starts to get repetitive. This is a key indicator that some of the code is ripe for reuse in a simple yet flexible base class. In fact, I've implemented just such a class, and in this article I'm going to show you how to use it. Keep in mind, I've designed this class for simplicity. If you need access to some of the richer features of the XML Serializer such as customized type mappings or responding to deserialization events, you'll have to extend the base class to support this functionality. Also, if your class already inherits from some other base class, then this class simply won't work for you. That said, I've found this class to handle my needs in most cases, where I just want a quick and easy way to save my object's state as XML.

Ok, let's dive right in to some code. The following block shows a typical use of the XmlSerializer.

public static Person Load(string fullPath)
{
  XmlSerializer ser = null;
  using (Stream s = File.OpenRead(fullPath))
  {
    ser = new XmlSerializer(typeof(Person));
    return (Person)ser.Deserialize(s);
  }
}
public void Save(string fullPath)
{
  XmlSerializer ser = null;
  using (Stream s = File.OpenWrite(fullPath))
  {
    ser = new XmlSerializer(typeof(Person));
    ser.Serialize(s, this);
  }
}
public void Foo()
{
  Person thePerson = Load(@"c:\person.xml");
   // ...do something meaningful with the object here
  thePerson.Save(@"c:\person.xml");
}

Note that the C# using construct takes care of disposing the FileStream for us. This sure doesn't seem like much code write, until you realize that you're writing Load and Save methods for every Xml Serializable class you write! Using the XmlSerializationBase class, you no longer have to do this.

using Romney.Christian.Xml.Serialization;

public class Person: XmlSerializationBase
{
   // ...no need to write Load/Save code because we're using the base class
}
 
public void Foo()
{
   Person thePerson = (Person)Person.Load(@"c:\person.xml", typeof(Person));
   // ...do something meaningful with the object here
   thePerson.Save(@"c:\person.xml");
}

The abstract base class makes use of polymorphism and reflection to accomplish its tasks. In fact, the Load overloads all return an XmlSerializationBase, so the result of this method call must always be cast to the appropriate type before using them as normal.

One final point of interest: some of the Load and Save overloads take a boolean parameter, AutoClose, which lets you specify whether or not to close the underlying data source after de/persistance. The overloads which do not accept a boolean delegate to the boolean versions passing in true (close the data source) as the final parameter. Using the boolean versions can eliminate the overhead of an additional method call at the cost of an added parameter.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

lechonsazo
Web Developer
United States United States
I am the Senior Manager, Ecommerce Development for Certified Vacations, which develops and maintains websites for some of the biggest names in the travel industry.
I've been programming Microsoft platforms for over 7 years. My interests include angle brackets and my family.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 2 Jun 2003
Article Copyright 2003 by lechonsazo
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid