A while back I posted code on a method that would allow for serializing any object that was serializable into XML called 'A generic serialization method'. I had some requests on how the XML could be deserialized back into an object instance such as once the XML is passed between systems or stored and reloaded by an application at a later time. The following is a generic deserialization method that will take the XML document as a string and deserialize it back into an object instance.
/// <summary>
/// Deserialize an XML document into the specified object. This can only work
/// on objects that are Serializable.
///
/// Be sure to type cast the object being returned. For example:
/// MyObject obj = (MyObject)UtilityFunctions.DeserializeFromXML(xmlOfObject, typeof(MyObject));
/// </summary>
/// <param name="objToDeserialize">The full XML document representation of the object as a string.</param>
/// <param name="objectType">The type of the object that the XML will be deserialized into.</param>
/// <returns>An object reference to the deserialized object instance.</returns>
public static object DeserializeFromXML(string objToDeserialize, Type objectType) {
System.Xml.Serialization.XmlSerializer mySerializer = null;
XmlTextReader reader = null;
try {
//Instantiate the Serializer with the type of object that is being deserialized.
mySerializer = new System.Xml.Serialization.XmlSerializer(objectType);
reader = new XmlTextReader(objToDeserialize, XmlNodeType.Document, null);
//Serialize the object to xml
byte[] objData = System.Text.ASCIIEncoding.ASCII.GetBytes(objToDeserialize);
object result = mySerializer.Deserialize(reader);
reader.Close();
return result;
}
catch (Exception ex) {
throw ex;
}
finally {
if (reader != null) { reader.Close(); }
}
}
When a caller calls this method be sure to remember to cast the return value into the type of object being deserialized. Below is a simple example object and a code snipet on how to call the SerializeToXML and DeserializeFromXML methods.
[Serializable()]
public class SerializeMe{
private int _prop1 = 0;
private string _prop2 = "prop2";
public int Prop1{
get{return _prop1;}
set{_prop1 = value;}
}
public string Prop2{
get{return _prop2;}
set{_prop2 = value;}
}
}
Example code snippet:
SerializeMe cls = new SerializeMe();
cls.Prop2 = "testing";
string test = UtilityFunctions.SerializeToXML(cls);
SerializeMe cls2 = (SerializeMe)UtilityFunctions.DeserializeFromXML(test, typeof(SerializeMe));