5,427,813 members and growing! (16,901 online)
Email Password   helpLost your password?
Languages » XML » XML/XSLT     Intermediate

Wrap the .NET Xml Serialization Framework

By lechonsazo

This lightweight base class trivializes Xml Serialization and eliminates duplication in projects with multiple serializable classes.
C#, Windows, .NET 1.0, .NET 1.1, .NETVisual Studio, VS.NET2003, Dev

Posted: 1 Jun 2003
Updated: 1 Jun 2003
Views: 29,754
Bookmarked: 13 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
11 votes for this Article.
Popularity: 2.63 Rating: 2.53 out of 5
2 votes, 18.2%
1
5 votes, 45.5%
2
0 votes, 0.0%
3
1 vote, 9.1%
4
3 votes, 27.3%
5

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

About the Author

lechonsazo


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.
Occupation: Web Developer
Location: United States United States

Other popular XML articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
  (Refresh) 
Subject  Author Date 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Jun 2003
Editor: Chris Maunder
Copyright 2003 by lechonsazo
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project