Building an Xml Serialization Provider
While building Galactic Wars 3 version 2.0, I quickly ran into a serious problem with Xml serialization and more specifically deserialization. A few months ago I rolled my own solution for serializing data to and from Xml because the built in classes were bloated and yet not feature rich. A week or two ago I managed to get my class (XmlProvider) to compile for the Zune and Xbox 360. But there was still a problem…
- References
The first problem (the reason for the creation of XmlProvider) was that the built-in classes could not handle references. Every object had to be serialized straight through from top to bottom. Thus if you had an object with two properties that referenced the same object (in memory), the object would be serialized twice. - Inheritance
The new problem is that with XmlProvider, deserialization was based on the information given by property attributes in your code. This is limiting because you may not know at compile time what exact type of object your property will be holding a reference to. In Galactic Wars 3 this is a problem when I am saving the profile of the user and want to save his specific ship.
So what is the solution? Start from scratch of course and solve these two problems at once! The first one is easy: provide a mechanism with which to uniquely identify any objects in memory and in Xml. We can then build a cache which we can reference from as we find objects with references. The solution to the second problem is also simple: rely on the type name in the Xml rather than the type on the property’s attributes.
To start us off, we will need an attribute with which we can decorate our classes. We will call this class XmlNodeAttribute since anything utilizing it will become an XmlNode. The code is fairly straight forward as shown below. We need a simple enumeration to define what type of Xml node to create because objects with properties need to be treated differently than simple types like boolean, string, int, et cetera.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class XmlNodeAttribute : Attribute{ public XmlNodeAttribute(string name, XmlNodeType nodeType) { Name = name; NodeType = nodeType; } public XmlNodeType NodeType { get; set; } public string Name { get; set; } } public enum XmlNodeType{ Complex, Simple } |
Next we can setup our XmlProvider class…
Tags: Data, Deserialization, FGF, Serialization, Tutorials, Xml