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();

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.