David’s gearing up a conversation about XML Serialization of application settings (see XML Serialization - Conversion of XML Documents and Streams to Common Language Runtime Objects and Vice Versa),
and I thought I’d offer up a class that I use heavily in my day to day
development. It’s a serialization helper, and it just contains some
static methods for serializing objects back and forth from/to XML.
Updated: Changed to use Encoding.UTF8 as per Scott G.'s suggestion.
public class SerializationHelper
{
/// <summary>
/// Serialize an object into XML
/// </summary>
/// <param name="serializableObject">Object that can be serialized</param>
/// <returns>Serial XML representation</returns>
public static string XmlSerialize(object serializableObject)
{
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
System.IO.MemoryStream aMemStr = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null);
serializer.Serialize(writer,serializableObject);
string strXml = System.Text.Encoding.UTF8.GetString(aMemStr.ToArray());
return strXml;
}
/// <summary>
/// Restore (Deserialize) an object, given an XML string
/// </summary>
/// <param name="xmlString">XML</param>
/// <param name="serializableObject">Object to restore as</param>
public static object XmlDeSerialize(string xmlString, object serializableObject)
{
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
System.IO.MemoryStream aStream = new
System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString));
return serializer.Deserialize(aStream);
}
/// <summary>
/// Restore (Deserialize) an object, given an XML string
/// </summary>
/// <param name="xmlString">XML</param>
/// <param name="serializableObject">Type of object to restore as</param>
public static object XmlDeSerialize(string xmlString, Type objectType)
{
XmlSerializer serializer = new XmlSerializer(objectType);
System.IO.MemoryStream aStream = new
System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString));
return serializer.Deserialize(aStream);
}
}
To Serialize an object:
[AirCode]
SomeObjectType someObject = new SomeObjectType();
String someString = SerializationHelper.XmlSerialize(someObject)
To DeSerialize an object
[AirCode]
someObject = (SomeObjectType) SerializationHelper.XmlDeSerialize(someString, typeof(SomeObjectType));
-Brendan
Posted
Tue, Mar 1 2005 11:03 AM
by
Brendan Tompkins