1.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 DataGridcontrol 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 1-3 shows the appearance of a typical DataGrid in a browser. Example 1-7 shows the XML used for the recipe. Examples Example 1-8 through Example 1-10 show the .aspx and code-behind files for an application that produces this result.

DataGrid with XML data output

Figure 1-3. DataGrid with XML data output

Discussion

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

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, there is a single node in the XML 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. It is always best to reference the table by name instead of by index because the index value can change if the structure of the data changes.

It’s no secret that the DataGrid control is one of the most flexible controls provided with ASP.NET. It outputs a complete HTML table with the bound data displayed in its cells. When used with a rich data source, such as a data reader, a DataTable, or a DataSet, the DataGrid can automatically generate columns for the data, complete with column headers (see Recipe 1.2). Unfortunately, its default appearance and automatic behavior rarely meet the needs of a project. In this section we discuss some ways to make changing the default appearance and behavior a little easier, especially as it relates to displaying XML data.

First, provide more flexibility for your graphical design team to achieve the desired appearance by defining an asp:DataGrid with HeaderStyle, ItemStyle, AlternatingItemStyle, and Columns elements, as shown in Example 1-8.

In this example, we use the BorderColor and the BorderWidth attributes of the asp:DataGrid element to define the color and width of the border around the table generated by the DataGrid. The AutoGenerateColumns attribute is set to False to allow us to define the columns that will be displayed in the grid. If this attribute is set to True, the DataGrid will automatically generate columns as a function of the data bound to the grid.

The HeaderStyle element and its attributes are used to define the appearance of the grid header. The ItemStyle element and its attributes are used to define the appearance of the even-numbered rows in the grid. The AlternatingItemStyle element and its attributes are used to define the appearance of the odd-numbered rows in the grid. If you do not need to output the data using alternating styles, then omit the AlternatingItemStyle element.

The Columns element is used to define the columns in the grid, their headings, and the data fields that are bound to each of the columns. For each column that is to appear in the grid, an asp:BoundColumn element must be included. At a minimum, each asp:BoundColumn element must define the HeaderTitle attribute and the DataField attribute. The HeaderTitle attribute is set to the label for the column. The DataField attribute is set to the name of the data field in the dataset whose data is to be bound to the column. In addition, many other attributes can be included to define alignment, fonts, stylesheet classes, and the like as required to achieve the desired appearance.

Example 1-7. XML data used for example

<Root>
  <Book>
    <BookID>1</BookID>
    <Title>Access Cookbook</Title>
    <ISBN>0-596-00084-7</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
    <BookID>2</BookID>
    <Title>Perl Cookbook</Title>
    <ISBN>1-565-92243-3</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
    <BookID>3</BookID>
    <Title>Java Cookbook</Title>
    <ISBN>0-596-00170-3</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
    <BookID>4</BookID>
    <Title>JavaScript Application Cookbook</Title>
    <ISBN>1-565-92577-7</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
    <BookID>5</BookID>
    <Title>VB .Net Language in a Nutshell</Title>
    <ISBN>0-596-00092-8</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
    <BookID>6</BookID>
    <Title>Programming Visual Basic .Net</Title>
    <ISBN>0-596-00093-6</ISBN>
    <Publisher>O'Reilly</Publisher>
  </Book>
    <Book>
      <BookID>7</BookID>
      <Title>Programming C#</Title>
      <ISBN>0-596-00117-7</ISBN>
      <Publisher>O'Reilly</Publisher>
    </Book>
    <Book>
      <BookID>8</BookID>
      <Title>.Net Framework Essentials</Title>
      <ISBN>0-596-00165-7</ISBN>
      <Publisher>O'Reilly</Publisher>
    </Book>
    <Book>
      <BookID>9</BookID>
      <Title>COM and .Net Component Services</Title>
      <ISBN>0-596-00103-7</ISBN>
      <Publisher>O'Reilly</Publisher>
   </Book>
 </Root>

Example 1-8. DataGrid with XML data (.aspx)

<%@ Page Language="vb" AutoEventWireup="false" 
         Codebehind="CH01DataGridWithXMLVB.aspx.vb" 
         Inherits="ASPNetCookbook.VBExamples.CH01DataGridWithXMLVB" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>Datagrid With XML VB</title>
    <link rel="stylesheet" href="css/ASPNetCookbook.css">
  </head>
  <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">
    <form id="frmDatagrid" method="post" runat="server">
      <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td align="center">
            <img src="images/ASPNETCookbookHeading_blue.gif">
          </td>
        </tr>
        <tr>
          <td class="dividerLine">
            <img src="images/spacer.gif" height="6" border="0"></td>
        </tr>
      </table>
      <table width="90%" align="center" border="0">
        <tr>
          <td><img src="images/spacer.gif" height="10" border="0"></td>
        </tr>
        <tr>
          <td align="center" class="PageHeading">
             DataGrid Using Data From XML (VB)</td>
        </tr>
        <tr>
          <td><img src="images/spacer.gif" height="10" border="0"></td>
        </tr>
        <tr>
          <td align="center">
            <asp:DataGrid 
                                id="dgBooks" 
                                runat="server" 
                                BorderColor="000080" 
                                BorderWidth="2px"
                                AutoGenerateColumns="False"
                                width="100%">

                                <HeaderStyle 
                                  HorizontalAlign="Center" 
                                  ForeColor="#FFFFFF" 
                                  BackColor="#000080" 
                                  Font-Bold=true
                                  CssClass="TableHeader" /> 

                                <ItemStyle
                                  BackColor="#FFFFE0" 
                                  cssClass="TableCellNormal" />

                                <AlternatingItemStyle 
                                  BackColor="#FFFFFF" 
                                  cssClass="TableCellAlternating" />
                                

                                <Columns>
                                  <asp:BoundColumn HeaderText="Title" DataField="Title" />
                                  <asp:BoundColumn HeaderText="ISBN" DataField="ISBN" 
                                                   ItemStyle-HorizontalAlign="Center" />
                                  <asp:BoundColumn HeaderText="Publisher" DataField="Publisher"
                                                   ItemStyle-HorizontalAlign="Center" />
                                </Columns>
                              </asp:DataGrid>
          </td>
        </tr>
      </table>
    </form>
</body>
</html>

Example 1-9. DataGrid with XML data code-behind (.vb)

Option Explicit On 
Option Strict On
'-----------------------------------------------------------------------------
'
'   Module Name: CH01DataGridWithXMLVB.aspx.vb
'
'   Description: This class provides the code behind for
'                CH01DataGridWithXMLVB.aspx
'
'*****************************************************************************
Imports Microsoft.VisualBasic
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb

Namespace ASPNetCookbook.VBExamples
  Public Class CH01DataGridWithXMLVB
    Inherits System.Web.UI.Page

    'controls on form
    Protected dgBooks As System.Web.UI.WebControls.DataGrid

    '*************************************************************************
    '
    '   ROUTINE: Page_Load
    '
    '   DESCRIPTION: This routine provides the event handler for the page load
    '                event.  It is responsible for initializing the controls
    '                on the page.
    '
    '-------------------------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
            Handles MyBase.Load
      Const BOOK_TABLE As String = "Book"

      Dim dSet As DataSet
      Dim xmlFilename As String

      If (Not Page.IsPostBack) Then
        Try
          'get fully qualified path to the "books" xml document located
                            'in the xml directory
                            xmlFilename = Server.MapPath("xml") & "\books.xml"

                            'create a dataset and load the books xml document into it
                            dSet = New DataSet
                            dSet.ReadXml(xmlFilename)

                            'bind the dataset to the datagrid
                            dgBooks.DataSource = dSet.Tables(BOOK_TABLE)
                            dgBooks.DataBind( )

        Finally
          'cleanup
          If (Not IsNothing(dSet)) Then
            dSet.Dispose( )
          End If
        End Try
      End If
    End Sub  'Page_Load
  End Class  'CH01DataGridWithXMLVB
End Namespace

Example 1-10. DataGrid with XML data code-behind (.cs)

//----------------------------------------------------------------------------
//
//   Module Name: CH01DataGridWithXMLCS.aspx.cs
//
//   Description: This class provides the code behind for
//                CH01DataGridWithXMLCS.aspx
//
//****************************************************************************
using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;

namespace ASPNetCookbook.CSExamples
{
  public class CH01DataGridWithXMLCS : System.Web.UI.Page
  {
    // controls on form
    protected System.Web.UI.WebControls.DataGrid dgBooks;

    //************************************************************************
    //
    //   ROUTINE: Page_Load
    //
    //   DESCRIPTION: This routine provides the event handler for the page
    //                load event.  It is responsible for initializing the
    //                controls on the page.
    //
    //------------------------------------------------------------------------
    private void Page_Load(object sender, System.EventArgs e)
    {
      const String BOOK_TABLE = "Book";

      DataSet dSet = null;
      String xmlFilename = null;

      if (!Page.IsPostBack)
      {
        try
        {
          // get fully qualified path to the "books" xml document located
                            // in the xml directory
                            xmlFilename = Server.MapPath("xml") + "\\books.xml";

                            // create a dataset and load the books xml document into it
                            dSet = new DataSet( );
                            dSet.ReadXml(xmlFilename);

                            // bind the dataset to the datagrid
                            dgBooks.DataSource = dSet.Tables[BOOK_TABLE];
                            dgBooks.DataBind( );
        }  // try

        finally
        {
          // cleanup
          if (dSet != null)
          {
            dSet.Dispose( );
          }
        }  // finally
      }
    }  // Page_Load
  }  // CH01DataGridWithXMLCS
}

Get ASP.NET Cookbook 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.