Friday, April 6, 2007

SQL 2005 XML Datatype for Serialize Object

In order to save xml deserialized object to SQL 2005, make sure it is "utf-8" encoding.


public string ToXml()
{
using(MemoryStream memStream = new MemoryStream())
{
XmlSerializer sr = new XmlSerializer(this.GetType());
sr.Serialize(memStream, this);
// NOTE: Using UTF8 Encoding to support saving to SQL 2005 Database


return System.Text.Encoding.UTF8.GetString(memStream.ToArray());
}
}


public static T XmlDeserialize(string xml)
{
if (string.IsNullOrEmpty(xml))
return default(T);

System.IO.Stream stream =
new System.IO.MemoryStream (System.Text.Encoding.UTF8.GetBytes(xml));

XmlSerializer sr = new XmlSerializer(typeof(T));

return (T)sr.Deserialize(stream);
}


I have issue on using on using "utf-16" which is a native xml serialization. Unicode (UTF-16) Encoding currently is not supported in XML DataType Columns (without Schemas). if including Root Element in XML Text.

References:
Retrieving Objects from SQL Server Using SQLXML and Serialization By Gianluca Nuzzo


No comments: