Sunday, September 12, 2010

Database, Reading an XML File into In-Memory Data Tables

Problem

You previously exported a DataSet to an XML file, and now you need to get it back.

Solution

Use the DataSet object's ReadXML() method to restore data from a previously generated XML export.

Discussion

Recipe 13.9 exports some XML and a related schema for a table with state-specific information. To read it back into a DataSet object, use the following code:
Dim stateSet As New Data.DataSet
 stateSet.ReadXmlSchema("c:\StateSchema.xml")
 stateSet.ReadXml("c:\StateInfo.xml")




You do not need to import a previously saved schema into a DataSet before retrieving the related data, but it helps. Without the schema, either you will have to recraft the column definitions in each DataTable object yourself, or you will have to refer to each data column by numeric position and without strong data typing. Reloading a previously saved schema takes care of a lot of the redesigning work for you. If your program will use a consistent schema regularly, you can save it internally in your application source code or in an application resource. You can also import schema and data files directly into a DataTable object, forgoing the larger DataSet object:
Dim stateTable As New Data.DataTable
 stateTable.ReadXmlSchema("c:\StateSchema.xml")
 stateTable.ReadXml("c:\StateInfo.xml")

Once you have imported the data, you can use that data just as if you had handcrafted it using ADO.NET objects or imported it from a standard database:
' ----- Process each imported state record.
 For Each stateInfo As Data.DataRow In stateTable.Rows()
    MsgBox(stateInfo!FullName)
 Next stateInfo

No comments: