Xml Serialization

If you want to store data, you often use a database. It’s very good way. But, sometimes you need to save too little amount of data that using a database is thoughtless. Another way to store data is to put it in a simple text file. One of the most convenient ways to do this is to use a XML file. It stores data in such a way, that you can easily access it later. XML files are used everywhere and for every type of usage. For example, two (or more) computers can communicate with XML files.

I am going to show you how you can convert your object to a XML file in order to save its data. This process if called serialization. There are many ways to serialize an object. I am going to show you how you can you do this by using the IXmlSerializable interface. It’s in System.Xml.Serialization namespace. You’ll need to include System.Xml namespace, too.

If you look at the source of this interface, you will probably see something like this:

The first method returns an object of type XmlSchema. It determines the schema of your future XML file. In our case, we won’t change this schema and our file will have the standard one. WriteXml method uses a XmlWriter object to determine what data and in what way will be stored in the file. ReadXml reads the file (by an XmlReader object) and changes the properties of your object depending of the read information.

Here’s our simple class that we will use:

Inheriting the IXmlSerializable interface, you should define its three methods. As we said earlier, we are not going to change the default XmlSchema, so this method will return null. In this case we have only to properties to store. Here is the proper way to do this:

Before showing how to implement the ReadXml method, I want to show you the real usage – how to serialize this object. Using the XmlSerializer object, we can do this. I want to say, that for the sake of serialization, your class must have a parameterless constructor!

This example creates the following XML file:

Now, in order to restore our object by this information in our XML file, we have to deserialize it by implementing the ReadXml method. We know the structure of the file, so it’s very easy.

Now, we are ready. The final step to reconstruct our object are here:

That’s it! Very nice! Using this interface, we can easily serialize whatever type of object and then to deserialize it.