.Net XML Serialization

Most of the saving and loading of MUD data in Basterne 2 was handled by low-level C functions that used a custom text file format for each data type. That is just a bad idea.

Save and load functions were typically dozens or hundreds of lines of code with lots of room for error and data loss. If a word was off by one space or a character was miscapitalized, a file load would fail and nothing could be done. Players of Basternae 2 probably remember pfile corruption issues with anything but fondness.

Every time we changed a file format by adding another value to an object, we had to build a translator that would convert the old file to the new version. Usually this wasn’t too hard, but it did result in a LOT of extra code lying around where it didn’t belong.

.Net makes this a lot better by giving us XML serialization.

With XML serialization, data is dumped out in a neat little XML file that can be read not only by our MUD server, but by just about anything that can read XML, which these days is just about every application in existence. Gone are the days of low-level custom file formats and painful data corruption issues (I hope).

So, how do we do it?

For example, I just rewrote the saving and loading of fraglists to use XML serialization. The code started as 174 lines of custom textfile saving and loading with lots of recursive looping to save and read the arrays containing numbers on the frag list by race and class.

Now the code looks like:

public void Load()
{
XmlSerializer serializer = new XmlSerializer( this.GetType() );
Stream stream = new FileStream( Database.SYSTEM_DIR + Database.FRAG_FILE, FileMode.Open,
FileAccess.Read, FileShare.None );
fraglist = (frag_data)serializer.Deserialize(stream);
stream.Close();
}

public void Save()
{
XmlSerializer serializer = new XmlSerializer( this.GetType() );
Stream stream = new FileStream( Database.SYSTEM_DIR + Database.FRAG_FILE, FileMode.Create,
FileAccess.Write, FileShare.None );
serializer.Serialize( stream, this );
stream.Close();
}

Cleaner and better, just the way we like it. I still hate the way WordPress formats source code.

The compile error count is now down to 1,649.

1 thought on “.Net XML Serialization

  1. Rick

    I have messed around with the original diku gamma code base a few times and I’ve just started playing with xml. I was actually looking into converting help files, player files, etc to xml when I came across this website and all the work that has been done here. Is there any chance you could send me an email and I could pick you brain about this project? I am very impressed with what has been done here and would like your advice.

    Thanks,
    Rick

Comments are closed.