Posted on Wednesday March 14, 2012

Serializing an object to XML snippet

I’ve written this same snippet so many times I’ve decided to shove it here to save my fingers a few calories in future. It’s nothing special, just a way of serializing an object to XML.

string ToXml(object instance)
{
	XmlSerializer serializer = new XmlSerializer(instance.GetType());
	StringBuilder builder = new StringBuilder();
	using (StringWriter writer = new StringWriter(builder))
	{
		serializer.Serialize(writer, instance);
		return builder.ToString();
	}
}