Saving and Loading Data: XmlSerializer

What to expect
Data can be saved in many different formats. Xml is one of the more standardized ones. There are several different ways to parse an xml file. The XmlSerializer is one of the easiest way included directly with every .NET/mono installation.

The goal of this tutorial will be to save and load data with the following xml structure.

Preparing the Monster class
The XmlSerializer automatically knows about each public variable or read/write property in any type you can throw at it. Primitive types like string, int, float and enums can be automatically serialized.

Through attributes you can further tell the XmlSerializer about how you want the xml to be parsed. By default every variable will be translated to one xml element (e.g. 5). If you want it to be parsed as attribute ( e.g.  ) you have to use XmlAttribute(name) like in the sample.

The MonsterContainer
To store all of the monsters we need a list of all of them.

The root element of each xml file should be annotated with the XmlRoot attribute. This way the XmlSerializer will know which XmlElement is to be expected as the root element. A list is just like an array with the added bonus of being able to add new elements easily.

With XmlArray and XmlArrayItem you can declare how the list should be represented within the xml file.

Writing data
Make sure you call the Close or Dispose method after writing else the file you just created will only be created in memory and will never be actually written to the file.

Convenience
I personally like putting read and write methods in the root class like this.

Deployment
For this code to work after being deployed you need to take additional care.

Standalone Player
After you deployed your application your Application.dataPath will point to "(PathToExecutable)/executable_Data". So you need to take care to store your monsters.xml there for the application to find it.

Webplayer
The webplayer can't access files on any computer directly so using the methods described before to read/write data won't work here. To load any data you need to use the WWW class.

Example that loads the monsters.xml file directly from where your webplayer html is located.

iOS Devices
A NullReferenceException will be raised if you're using List in your MonsterContainer class, use an array instead. Similarly the same exception is raised if you're using get and set to implement properties in the class you're trying to serialize.

Additional Notes

 * You have to define at least one constructor without parameters for the XmlSerializer to work correctly
 * If your class contains a struct or class Variable that contains the supported data types the XmlSerializer can automatically serialize it too.
 * More information about the the xmlserializer and all its special features can be found here