Recently I was in the need to serialize a DataTable
as a string for further processing (storing in a file).
So I asked myself: How to serialize a DataTa
You can also do this.
DataTable dt = new DataTable()
//... Fill Datatable from SQL or a thousand other places you have seen on the net.
Response.ContentType = "text/xml";
dt.WriteXml(Response.OutputStream);
Response.Flush();
Response.End();
Documentation found at
http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml(v=VS.100).aspx
I would suggest NOT to serialize the DataTable and use custom entities for persistence/contracts to avoid difference in implementation details between .Net versions. The XML schema of the DataTable class is undocumented implementation detail that you should not rely on.
Here is the code I wrote to perform the task of serializing a DataTable
into a string:
public static string SerializeTableToString( DataTable table )
{
if (table == null)
{
return null;
}
else
{
using (var sw = new StringWriter())
using (var tw = new XmlTextWriter(sw))
{
// Must set name for serialization to succeed.
table.TableName = @"MyTable";
// --
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
tw.WriteStartElement(@"data");
((IXmlSerializable)table).WriteXml(tw);
tw.WriteEndElement();
tw.WriteEndDocument();
// --
tw.Flush();
tw.Close();
sw.Flush();
return sw.ToString();
}
}
}
Hopefully this is useful for someone somewhere out there.
(Please note that I asked in the past whether it is OK to post snippets and got replies that this should be OK; correct me if I am wrong on that - thanks!)
You can also try writing out the DataTable to XML which works just as nicely:
Dim dt As DataTable
Dim DataTableAsXMLString As String
'...code to populate DataTable
Using sw As New StringWriter()
dt.WriteXml(sw)
DataTableAsXMLString = sw.ToString()
End Using
...then if needed you can convert the XML right back to a DataTable:
Dim ds As New DataSet
Dim dt2 As DataTable
Using sr As New StringReader(DataTableAsXMLString)
ds.ReadXml(sr)
dt2 = ds.Tables(0)
End Using