The contents of an ADO.NET DataSet can be obtained from an XML stream or document.
This capability greatly simplifies the retrieval of data from any Xml data source, such as an Xml Web Service. Once in the DataSet, the information is readily exposed in the same manner as in a typical database, using tables, columns, and relations, the structures of which are derived from the Xml schema.
The following briefly describes the steps to retrieve information from an Xml file into a DataSet.
- First, set up a DataSet.
DataSet myData = new DataSet ( );
Dim myData as New DataSet ( ) |
|
C# |
VB |
- Then, populate the DataSet with the ReadXml method.
myData.ReadXml ( Server.MapPath ( "~/adonet/demos/authors.xml" ) );
myData.ReadXml ( Server.MapPath ( "~/adonet/demos/authors.xml" ) ) |
|
C# |
VB |
The DataSet now contains a DataTable that holds the contents of the Xml file. That’s all there is to it, really.
And because the data is stored as a collection of rows and columns in the table, you can iterate through and display the contents of the DataSet using simple foreach statements.
foreach ( DataTable table in myData.Tables ) {
foreach ( DataRow row in table.Rows ) {
foreach ( DataColumn col in table.Columns ) {
Response.Write ( row [ col ].ToString ( ) );
}
}
}
foreach table as DataTable in myData.Tables
foreach row as DataRow in table.Rows
foreach col as DataColumn in table.Columns
Response.Write ( row ( col ).ToString ( ) )
next
next
next |
|
C# |
VB |
The method described above uses generic array notation ( ex. row [ col ]
) to access the data in the tables, rows, and columns collections of the DataSet. This makes the method applicable to any DataSet, and is particularly useful when the table and field names are unknown beforehand.
The below example demonstrates how to load an Xml file into a Dataset, then iterates thru and displays the contents of the DataSet using simple foreach loops as described above.
NOTE: This example uses one of the overloaded versions of the ReadXml method. For other examples that may be available, see the individual overload topics.
Show me
This workshop includes a "real-world" Web storefront application, Books and more ..., that demonstrates using data retrieved from an Xml Web Service and rendered into Web Forms pages.
Displaying Information from a Database