How to serialize a DataTable to a string?

前端 未结 4 1314
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 08:47

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

相关标签:
4条回答
  • 2020-12-15 09:26

    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

    0 讨论(0)
  • 2020-12-15 09:39

    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.

    0 讨论(0)
  • 2020-12-15 09:40

    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!)

    0 讨论(0)
  • 2020-12-15 09:42

    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
    
    0 讨论(0)
提交回复
热议问题