Serializing Xml to Sql Server xml DataType
In SQLServer2005 there is an xml DataType that is used to – yes, you guessed it – store xml. In .NET development, of course one of the first things that comes to mind is storing serialized objects in a field like this.
Of course, you can write a string that is xml directly to the database. So I thought I'd record the steps to get from an object to a string directly since I didn't see it on the blogosphere anywhere. You can pass it through a MemoryStream, or a StringWriter, but the StringWriter is easier. Here's the reference codebase:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
XmlSerializer xmlSer = new XmlSerializer(typeof(MyObject));
StringWriter sw = new StringWriter(System.Globalization.CultureInfo.CurrentUICulture);
XmlTextWriter xmlTw = new XmlTextWriter(sw);
lock(xmlTw)
{
xmlSer.Serialize(xmlTw, myobject);
}
xmlTw.Flush();
string xml = sw.ToString();



Comments