|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionThe .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 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 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 One final point of interest: some of the Load and Save overloads take a boolean parameter,
|
|||||||||||||||||||||||||||||||||||