VB.Net向/从XML文件读写DataTable [英] VB.Net write and read DataTable to/from XML-file
问题描述
我正在尝试将DataTable写入XML文件,然后使用以下VB.Net代码将数据从XML文件读取到另一个DataTable,我收到错误消息: DataTable不支持架构推断来自Xml。:
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.":
dt1.WriteXml(fileName:=xf, writeHierarchy:=True)
Dim dt2 = New Data.DataTable(dt1.TableName)
dt2 = ds.Tables(0)
dt2.ReadXml(fileName:=xf)
我可以通过将文件读入DataSet来解决我的问题,但我想了解其中的区别:
I could solve my problem with read the file into a DataSet, but I would like to understand the difference:
Dim ds = New Data.DataSet()
ds.ReadXml(fileName:=xf)
Dim dt2 = ds.Tables(0)
有人可以告诉我吗?
推荐答案
我知道很久以前就问过这个问题,但是几天前我也遇到了同样的问题。
I know this question asked long time ago, but I had same problem few days ago.
您必须设置 TableName $
DataTable
的c $ c>在导出之前(写 xml
)。
You have to set TableName
for DataTable
before exporting (writing xml
).
示例:
dt1.TableName = "MyDataTable"
dt1.WriteXmlSchema(Application.StartupPath + "\test_sh.xml", True)
dt1.WriteXml(Application.StartupPath + "\test_dt.xml", True)
然后读取(从 xml
导入)回到新的 DataTable
中:
And, for read (import from xml
) back in new DataTable
:
dt2 = New DataTable
dt2.ReadXmlSchema(Application.StartupPath + "\test_sh.xml")
dt2.ReadXml(Application.StartupPath + "\test_dt.xml")
然后填充您的 GridView
或您还需要什么。
And then populate Your GridView
or what else You need.
TableName
dt2
将自动从架构文件( test_sh.xml
)中提取。在这种情况下, MyDataTable
就像在 dt1.TableName
中设置的一样。
TableName
for dt2
will be automatically pulled from schema file (test_sh.xml
). In this case MyDataTable
, like was set in dt1.TableName
.
保存 schema
也是重要,否则您将无法阅读 xml
返回表格。
It's important to save schema
, too, or You can't read xml
back in table.
这篇关于VB.Net向/从XML文件读写DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!