如何编写/加载我的数据集到/从XML

时间:2016-03-25 01:07:29

标签: .net xml vb.net vba

我目前有一张桌子可以从我的Stocklist App系统中的表格中获取输入。

我希望能够将表中的数据保存到XML文件中,以备下次用户打开程序时再次加载。

我正在使用的当前代码是......

Dim entryno As Integer = 1
IDColumn.Table.WriteXml("C:\Users\User\Documents\Stocklist\XML\" & entryno & ".xml")
entryno += 1

但是没有创造出什么?

我的数据集名为“StockdataDataSet.xsd”

我的数据名称为“DataTable1”

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这是一个使用硬编码数据的简单示例,因此您可以看到我在说什么。放置一个断点,在Console.WriteLine中注明,然后检查DataSet。

Dim fileName As String = IO.Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory, "MyData.xml")

Dim ds As New DataSet
Dim dt As New DataTable With {.TableName = "Person"}
dt.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
dt.Columns.Add(New DataColumn With {.ColumnName = "MiddleName", .DataType = GetType(String)})
dt.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})

dt.Rows.Add(New Object() {"Karen", "Ann", "Payne"})
dt.Rows.Add(New Object() {"Kevin", "S", "Gallagher"})
dt.Rows.Add(New Object() {"Mary", "D", "Jones"})

ds.Tables.Add(dt)

ds.WriteXml(fileName)
Console.WriteLine("place a break point here")
ds.Clear()
ds.ReadXml(fileName)
Console.WriteLine("place a break point here")

结果

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Person>
    <FirstName>Karen</FirstName>
    <MiddleName>Ann</MiddleName>
    <LastName>Payne</LastName>
  </Person>
  <Person>
    <FirstName>Kevin</FirstName>
    <MiddleName>S</MiddleName>
    <LastName>Gallagher</LastName>
  </Person>
  <Person>
    <FirstName>Mary</FirstName>
    <MiddleName>D</MiddleName>
    <LastName>Jones</LastName>
  </Person>
</NewDataSet>

注意NewDataSet的DataSet名称,让我们通过创建数据集来改变它,如下所示

Dim ds As New DataSet With {.DataSetName = "People"}

结果

<?xml version="1.0" standalone="yes"?>
<People>
  <Person>
    <FirstName>Karen</FirstName>
    <MiddleName>Ann</MiddleName>
    <LastName>Payne</LastName>
  </Person>
  <Person>
    <FirstName>Kevin</FirstName>
    <MiddleName>S</MiddleName>
    <LastName>Gallagher</LastName>
  </Person>
  <Person>
    <FirstName>Mary</FirstName>
    <MiddleName>D</MiddleName>
    <LastName>Jones</LastName>
  </Person>
</People>