GeekZilla
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; } }
Paul is the COO of kwiboo ltd and has more than 20 years 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.
Comments
mcgurk said:
Not too bad. But where's the virtual overload with the StreamingContext object? Come on, dude, get with it. I got base class functionality to override, and yours is severely lacking!
phayman said:
Mcgurk, Feel free post an example or a link to your base class.
Paul
larsw said:
This can be made even less intruding with extension methods in C# 3.0.
Scott Peterson said:
Couldnt you add something like this to a utility class to a utility library to avoid code duplication?
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; } }
phayman said:
Nice work Scott!
Fancy writing some articles for GeekZilla?