class.Serialize()
Handly little function which I include in most classes. This function returns the object serialized as XML, perfect for logging etc.
/// <summary>
/// Serialize this object
/// </summary>
/// <returns>XmlDocument containing the current information serialized</returns>
public System.Xml.XmlDocument Serialize()
{
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(this.GetType());
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Xml.XmlDocument serializedObject = new System.Xml.XmlDocument();
serializer.Serialize(writer, this);
serializedObject.LoadXml(writer.ToString());
return serializedObject;
}
Developments
Scott Peterson pointed out that the following code could a useful alternative. Good work Scott.
public class XMLSerializer<T> {
public System.Xml.XmlDocument Serialize(T obj) {
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(obj.GetType());
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Xml.XmlDocument serializedObject = new System.Xml.XmlDocument();
serializer.Serialize(writer, obj);
serializedObject.LoadXml(writer.ToString());
return serializedObject;
}
}
| Author |
: Paul Hayman |
| Published |
: Wednesday, 14 June, 2006 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.