2.4. Displaying Data from an XML File

Problem

You want a quick and convenient way to display data from an XML file.

Solution

Use a DataGrid control and the ReadXml method of the DataSet class.

In the .aspx file, add a DataGrid control for displaying the data.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Read the data from the XML file using the ReadXml method of the DataSet class.

  2. Bind the DataSet to the DataGrid control.

Figure 2-3 shows the appearance of a typical DataGrid in a browser. Example 2-7 shows the XML used for the recipe. Examples 2-8, 2-9 through 2-10 show the .aspx and code-behind files for an application that produces this result.

DataGrid with XML data output

Figure 2-3. DataGrid with XML data output

Discussion

The Page_Load method in the code-behind, shown in Examples 2-9 (VB) and 2-10 (C#), reads the data from the XML file using the ReadXml method of the DataSet class and then binds the DataSet to the DataGrid control.

Datasets are designed to support hierarchical data and can contain multiple tables of data. Because of this support, when data is loaded into the dataset, it is loaded into a Tables collection. In this example, a single node in the XML is called Book. The DataSet will automatically load the XML data into a table named Book. When binding the data to the DataGrid, you must reference the desired table if the DataSet contains more than one table. Reference ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.