Jump to content

  • Log In with Google      Sign In   
  • Create Account


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 10 June 2010 - 10:48 AM

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);
}
}
}




Sponsor:

#2 Nypyren   Crossbones+   -  Reputation: 4104

Like
0Likes
Like

Posted 10 June 2010 - 11:11 AM

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.

#3 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 10 June 2010 - 11:27 AM

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.

#4 SiCrane   Moderators   -  Reputation: 9539

Like
0Likes
Like

Posted 10 June 2010 - 11:31 AM

Your top level object would look like:

class TopLevel {
CameraSettings camera_settings;
EnemySettings enemy_settings;
}

Just serialize a TopLevel object.

#5 Nypyren   Crossbones+   -  Reputation: 4104

Like
0Likes
Like

Posted 10 June 2010 - 11:45 AM

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.

#6 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 10 June 2010 - 11:41 PM

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]

#7 Nypyren   Crossbones+   -  Reputation: 4104

Like
0Likes
Like

Posted 11 June 2010 - 08:22 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.

#8 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 11 June 2010 - 10:36 AM

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[i].Load();
}
}

public void Save()
{
for (int i = 0; i < settings.Count; ++i)
{
settings[i].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?

#9 SiCrane   Moderators   -  Reputation: 9539

Like
0Likes
Like

Posted 11 June 2010 - 11:09 AM

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?

#10 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 11 June 2010 - 11:20 AM

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?

#11 SiCrane   Moderators   -  Reputation: 9539

Like
0Likes
Like

Posted 12 June 2010 - 02:42 AM

This is more flexible how? What does any of that extra code actually gain you?

#12 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 12 June 2010 - 11:07 PM

I'm guessing little to nothing. It was an attempt to save/load settings automatically using the overriding methods.

Is there no way to do this non-explicitly then?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS