VB.Net 向/从 XML 文件写入和读取数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29492196/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:58:45  来源:igfitidea点击:

VB.Net write and read DataTable to/from XML-file

vb.netdatatablexml

提问by afj

I'm trying to write a DataTable to an XML-file and read afterwards the data from the XML-file to another DataTable with the following VB.Net code, I'm getting the error "DataTable does not support schema inference from Xml.":

我正在尝试将数据表写入 XML 文件,然后使用以下 VB.Net 代码将数据从 XML 文件读取到另一个数据表,我收到错误“数据表不支持来自 Xml 的模式推断。 ”:

dt1.WriteXml(fileName:=xf, writeHierarchy:=True)  
Dim dt2 = New Data.DataTable(dt1.TableName)  
dt2 = ds.Tables(0)  
dt2.ReadXml(fileName:=xf)  

I could solve my problem with read the file into a DataSet, but I would like to understand the difference:

我可以通过将文件读入 DataSet 来解决我的问题,但我想了解其中的区别:

Dim ds = New Data.DataSet()  
ds.ReadXml(fileName:=xf)  
Dim dt2 = ds.Tables(0)  

Could anybody tell me?

有人能告诉我吗?

回答by nelek

I know this question asked long time ago, but I had same problem few days ago.

我知道很久以前就问过这个问题,但几天前我也遇到了同样的问题。

You have to set TableNamefor DataTablebefore exporting (writing xml).

你必须设定TableNameDataTable出口前(写入xml)。

Example :

例子 :

    dt1.TableName = "MyDataTable"
    dt1.WriteXmlSchema(Application.StartupPath + "\test_sh.xml", True)
    dt1.WriteXml(Application.StartupPath + "\test_dt.xml", True)

And, for read (import from xml) back in new DataTable:

并且,对于读取(从xml)回到 new DataTable

    dt2 = New DataTable
    dt2.ReadXmlSchema(Application.StartupPath + "\test_sh.xml")
    dt2.ReadXml(Application.StartupPath + "\test_dt.xml")

And then populate Your GridViewor what else You need.

然后填充您的GridView或您需要的其他内容。

TableNamefor dt2will be automatically pulled from schema file (test_sh.xml). In this case MyDataTable, like was set in dt1.TableName.

TableNamefordt2将自动从架构文件 ( test_sh.xml) 中提取。在这种情况下MyDataTable,like 被设置在dt1.TableName.

It's importantto save schema, too, or You can't read xmlback in table.

这是重要的节省schema,也还是不能读取xml的表背。