HowTo: Save and retrieve C# objects in XML

May 4, 2008 by Dave
 

I’ve spent a bit of time tweaking this XML Serialization class I wrote to make use of the System.Xml.Serialization objects Microsoft provides in .NET 2.0.

XML Serialization is a great way to store complex data types, and also a great alternative to binary serialization. Unfortunately, using these classes is not as straightforward as I would like, there isn’t any simple Save or Load methods, I’ve bridged that gap with a a small class that provides this functionality.

Basic Methods:

These are the two basic methods you would need to save and load an object from a file.

  • public static T Load<T>(string filename)
  • public static void Save<T>(string filename, T cls)

Additional Methods:

These methods are included for those that would like to bypass the files, and send objects directly over a different medium.

  • public static String SerializeObject<T>(T pObject)
  • public static T DeserializeObject<T>(String pXmlizedString)

Important Note:

Remember to wrap all of these methods in try-catch blocks and catch any exceptions thrown. If the file cannot be accessed, or there is an error during serialization, it will be passed on.

Code Example:

Load an object from file:

List MyList = null;
try
{
MyList = XSerial.Load<list>("MyList.xml");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
// make sure the object won't cause errors.
MyList = new List();
}
 
Save an object to file:
 
try
{
XSerial.Save</list><list>("MyList.xml", MyList);
}
catch (Exception e)
{
Console.WriteLine("Error Saving: " + e.Message);
// nothing can be done about recovery.
}</list>

Download Demo Project:

XMLSerialTest [ZIP] [Visual Studio 2008]

Comments