This blog will describe some of the learning experiences that I have with .NET, some personal projects that I'm working on, and whatever other topics tickle my fancy.
My Blog Links
Tuesday, August 10, 2004
Working on WinForms applications, I've written several projects that persist information out to a file. I have found that using XML serialization to save and load the file is an easy way of mapping a class to an XML document.
Serialization in the .NET Framework is very powerful and really pretty easy to implement. Although multiple serializers are available, like XML, binary, text, etc, I've used the XML method most often. Therefore, I created a base class called XmlPersistedClass that I use in projects that want to read and write XML files. The class implements Save and Load methods which encapsulate all of the code required to interact with serializers, readers, and writers.
Here's what it looks like:
As you can see this is an abstract class, so that to use it you must derive your own class from it. The Save method instantiates an XmlSerializer with the specified class type, then uses a TextWriter to serialize this class into. The Load method also uses an XmlSerializer and then a TextReader to create an instance of the class from what has been saved in the file.
The following is an example of creating a derived class:
In the code above, you'll notice that the [Serializable] attribute needs to be on the class, each property needs to have an XML serialization attribute as well, and you need a public default constructor for the class. If you don't specify an attribute for your property, then it defaults to [XmlElement]. However, [XmlAttribute], [XmlArray], and [XmlIgnore] are also very useful. Finally, XML serialization only persists property or data members that are public and have getters and setters. If your property doesn't follow these guidelines, then it won't be saved.
Usually, I overload the Save and Load methods to be type-specific rather than requiring types to be passed into those methods. Finally, this is a good example of methods that could really benefit from the Generics functionality coming out in Visual Studio 2005 -- at some point, I'll update the class to take advantage of that.
Comments: Post a Comment