[C#] [XML] Serializing/deserializing multiple classes?

Started by
10 comments, last by Spa8nky 13 years, 10 months ago
How can I serialize/deserialize many different class types using just one XML file?

For example if I have two settings classes, CameraSettings and EnemySettings how can I determine which class I am dealing with when serializing/deserializing their properties using just one XML file?

At the moment when dealing with just one class and I am doing the following for saving:

        private void XMLSave(object sender, System.EventArgs e)        {            object currentSettings = Game1.Instance.camera.Settings;            if (currentSettings == null)            {                return;            }            XmlWriterSettings settings = new XmlWriterSettings();            settings.Indent = true;            using (XmlWriter xmlWriter = XmlWriter.Create("AllSettings.xml", settings))            {                IntermediateSerializer.Serialize(xmlWriter, currentSettings, null);            }        }


and the following for loading:

        private void XMLLoad(object sender, System.EventArgs e)        {            Stream stream = null;            OpenFileDialog openFileDialog = new OpenFileDialog();            openFileDialog.CheckFileExists = true;            openFileDialog.CheckPathExists = true;            openFileDialog.InitialDirectory = "\\";            openFileDialog.Filter = "xml files (*.xml)|*.xml";            openFileDialog.FilterIndex = 2;            openFileDialog.RestoreDirectory = true;                        if (openFileDialog.ShowDialog() == DialogResult.OK)            {                try                {                    if ((stream = openFileDialog.OpenFile()) != null)                    {                        XmlReaderSettings settings = new XmlReaderSettings();                        settings.IgnoreComments = true;                        using (XmlReader reader = XmlReader.Create(stream, settings))                        {                            // - Clear the PhysX scene so no actors and entities are alive                            // - Create new entities/actors from settings                            Game1.Instance.camera.Settings = IntermediateSerializer.Deserialize<CameraSettings>(reader, null);                        }                    }                }                catch (Exception ex)                {                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);                }            }        }
Advertisement
I usually just make one top-level class which contains everything I need to deal with and (de)serialize a single instance of that class instead of trying to figure out which is which manually.
How would that work if I had different settings/properties for different classes?

For example camera settings:

Position
Yaw
Pitch

differ from enemy settings:

Position
Speed
Health

How would I know with one top-level class which one was which?

Apologies for not catching on to what you are saying, I'm a little perplexed by XML at this point.
Your top level object would look like:
class TopLevel {  CameraSettings camera_settings;  EnemySettings enemy_settings;}

Just serialize a TopLevel object.
The .Net serializers will serialize and deserialize entire hierarchies of objects (including proper handling for cyclic references) as long as every object in the hierarchy is serializable. It's pretty awesome.
Thanks guys.

I guess this means a defined save/load order for settings!

If I am to have my top level class that contains all settings to be saved/loaded, would "get set" accessors be ideal in this scenario when saving/loading settings?

For example with the camera class I could do the following:

        public CameraSettings Settings        {            get            {                // If settings class has not been created then create new instance                if (settings == null)                {                    settings = new CameraSettings();                }                // Write the necessary camera properties to the settings data                // Settings should only be called when saving                settings.Position = position;                return settings;            }            set            {                // Assign the new settings                settings = value;                // Change the camera properties based on the settings                Position = settings.Position;            }        }


Or would you recommend a different approach?

EDIT: Thinking about this some more, would it be better to just overwrite the existing camera (if there is one) by creating a new camera instance when the data is loaded? Or should I only do this if a camera instance has not been created?

[Edited by - Spa8nky on June 11, 2010 7:41:20 AM]
I'm only use the top level class as a *temporary* for (de)serialization, since it doesn't really provide any useful purpose other than that.
What do you think of the following idea?

I create a *temp* SaveData class that can hold any settings class that derives from an abstract settings class:

    [Serializable]    class SaveData    {        List<Settings> settings = new List<Settings>(100);        public SaveData() { }        public void Load()        {            for (int i = 0; i < settings.Count; ++i)            {                settings.Load();            }        }        public void Save()        {            for (int i = 0; i < settings.Count; ++i)            {                settings.Save();            }        }        public List<Settings> AllSettings        {            get { return settings; }            set { settings = value; }        }    }


The base settings class looks like the following:

    public abstract class Settings    {        public abstract void Load();        public abstract void Save();    }


and a derived camera settings class will look like this:

    [Serializable]    public class CameraSettings : Settings    {        public float FarClip = 1000.0f;        public float NearClip = 0.1f;        public float Pitch = 0.0f;                  // Pitch (radians)        public Vector3 Position = Vector3.Zero;        public float Sensitivity = 0.3f;        public float Yaw = 0.0f;                    // Yaw (radians)        [NonSerialized]        Camera camera;        public CameraSettings() { }        // Constructor requires associated camera        public CameraSettings(Camera camera)        {            this.camera = camera;        }        public override void Load()        {            Game1.Instance.camera = new Camera_FreeLook(this);        }        public override void Save()        {            FarClip = camera.FarClip;            NearClip = camera.NearClip;            Pitch = (float)Math.Asin(camera.ViewMatrix.M23);            Position = camera.Position;            Sensitivity = camera.LookSensitivity;            Yaw = (float)Math.Atan2(camera.ViewMatrix.M13, camera.ViewMatrix.M33);        }    }


The SaveData class can now be used for saving and loading any settings class by doing the following:

        private void XMLLoad(object sender, System.EventArgs e)        {            Stream stream = null;            OpenFileDialog openFileDialog = new OpenFileDialog();            openFileDialog.CheckFileExists = true;            openFileDialog.CheckPathExists = true;            openFileDialog.InitialDirectory = "\\";            openFileDialog.Filter = "xml files (*.xml)|*.xml";            openFileDialog.FilterIndex = 2;            openFileDialog.RestoreDirectory = true;                        if (openFileDialog.ShowDialog() == DialogResult.OK)            {                try                {                    if ((stream = openFileDialog.OpenFile()) != null)                    {                        XmlReaderSettings settings = new XmlReaderSettings();                        settings.IgnoreComments = true;                        using (XmlReader reader = XmlReader.Create(stream, settings))                        {                            // - Clear the PhysX scene so no actors and entities are alive                            // - Create new entities/actors from settings                            SaveData saveData = IntermediateSerializer.Deserialize<SaveData>(reader, null);                            saveData.Load();                        }                    }                }                catch (Exception ex)                {                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);                }            }        }        private void XMLSave(object sender, System.EventArgs e)        {            SaveData saveData = new SaveData();            saveData.AllSettings.Add(Game1.Instance.camera.Settings);            saveData.Save();            XmlWriterSettings settings = new XmlWriterSettings();            settings.Indent = true;            using (XmlWriter xmlWriter = XmlWriter.Create("AllSettings.xml", settings))            {                IntermediateSerializer.Serialize(xmlWriter, saveData, null);            }        }


What are your opinions on this approach? Have creating something hellish or is this a sensible idea?
I think you're seriously overthinking this. What value does a base settings class add over just making your individual settings classes serializable? If you lose the type information of dumping all the settings objects into a list, how are you going to get them stuck back into the right places?
Quote:
If you lose the type information of dumping all the settings objects into a list, how are you going to get them stuck back into the right places?


I was thinking along the lines of flexibility. Are you saying just keep it simple and only serialize/deserialize definite classes in a definite order?

This topic is closed to new replies.

Advertisement