Friday, October 9, 2009

C#: Serialize an object to Xml (string)

Especially useful if the object is not inheriting the [Serializable] attribute...


string GetSerializedXmlString(object obj)
{
MemoryStream memoryStream = new MemoryStream();
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xmlSerializer.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(memoryStream.ToArray());
}