.net 如何将数据表序列化为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2244655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serialize a DataTable to a string?
提问by Uwe Keim
Recently I was in the need to serialize a DataTableas a string for further processing (storing in a file).
最近我需要将 a 序列化为DataTable字符串以进行进一步处理(存储在文件中)。
So I asked myself: How to serialize a DataTable into a string?
于是我问自己:如何将一个DataTable序列化为一个字符串?
采纳答案by Uwe Keim
Here is the code I wrote to perform the task of serializing a DataTableinto a string:
这是我为执行将 a 序列DataTable化为字符串而编写的代码:
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 pastwhether it is OK to post snippets and got replies that this should be OK; correct me if I am wrong on that - thanks!)
(请注意,我过去曾问过是否可以发布片段,并得到回复说这应该可以;如果我错了,请纠正我 - 谢谢!)
回答by atconway
You can also try writing out the DataTable to XML which works just as nicely:
您还可以尝试将 DataTable 写出到 XML 中,这样也能很好地工作:
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:
...然后,如果需要,您可以将 XML 转换回 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
回答by Devon
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
http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml(v=VS.100).aspx
回答by u109919
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.
我建议不要序列化 DataTable 并使用自定义实体进行持久性/合同,以避免.Net 版本之间的实现细节差异。DataTable 类的 XML 架构是您不应依赖的未记录的实现细节。

