How to serialize and save an object in a database as Xml using Linq to SQL

I used FileStream to serialize an object in Xml and save to disk

Stream str = new FileStream(@"serializedstate.xml", FileMode.OpenOrCreate) XmlSerializer x = new XmlSerializer(typeof(GridState)); x.Serialize(str, new GridState { GridName= txtGridName.Text, GridColumns = GetGridColumnStates() }); 

This works fine and an Xml file is created on disk. How to save serialized object as Xml in XML column of Sql Server 2008 database using Linq to SQL? And how to deserialize the same from a database?

+6
c # linq-to-sql xml-serialization
source share
2 answers

For serialization in XElement

  XmlSerializer x = new XmlSerializer(typeof(GridState)); XDocument doc = new XDocument(); using (XmlWriter xw = doc.CreateWriter()) { x.Serialize(xw, new GridState { GridName= txtGridName.Text, GridColumns = GetGridColumnStates() }); xw.Close(); } XElement el = doc.Root; 

To deserialize

  using (XmlReader xr = el.CreateReader()) { GridState myDeserializedObject = x.Deserialize(xr) as GridState; xr.Close(); } 
+7
source share

In sql, you must have a colum type of type XML, and in linq, the Colum type must be XElement, which you can manipulate throw Linq with.

0
source share

All Articles