Thursday, July 16, 2009

Generic XML Serialization / De-Searialization

Generic Serialize and Deserialize Methods:

public static XmlDocument Serialize<T>(T xmlObject)
{
var xmlDocument = new XmlDocument();
var xml = new StringBuilder();
var serializer = new XmlSerializer(typeof(T));
var writer = new StringWriter(xml);
serializer.Serialize(writer, xmlObject);
xmlDocument.LoadXml(xml.ToString());
return xmlDocument;
}

public static T Deserialize<T>(XmlDocument xmlDocument)
{
T result;
XmlSerializer serializer = new XmlSerializer(typeof(T));

using (StringReader stringReader = new StringReader(xmlDocument.InnerXml))
{
using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
{
result = (T) serializer.Deserialize(xmlReader);
xmlReader.Close();
}
stringReader.Close();
}

return result;
}


Sample Usage:

//Serialize
XmlDocument xmlPerson = Serialize(person);

//Deserialize
Person anotherPerson = Deserialize<Person>(xmlPerson);