Recipe 2.5. 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.

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 the table by name instead of by index because the index value can change if the structure of the data changes.

The DataGrid control is one of the more 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 2.2 for an example using a GridView but in which you can easily substitute a DataGrid instead). 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 2-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.

In some cases, it is valid to have the AutoGenerateColumns attribute set to true and, as described in this recipe, define columns that will be displayed in the grid. This combined approach can be useful if you want to add another column to the ones automatically generated. When improperly done, it can result in duplicate columns.


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 bound to each of the columns. For each column appearing 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.

See Also

Recipe 2.2

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

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

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02DataGridWithXMLVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02DataGridWithXMLVB" Title="Datagrid With XML" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > DataGrid Using Data From XML (VB) </div> <asp:DataGrid  Runat="server"  BorderColor="#000080" BorderWidth="2px"  AutoGenerateColumns="False"  Width="90%" HorizontalAlign="Center" > <HeaderStyle HorizontalAlign="Center"  Css /> <ItemStyle Css /> <AlternatingItemStyle Css /> <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> </asp:Content> 

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

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02DataGridWithXMLVB.aspx ''' </summary> Partial Class CH02DataGridWithXMLVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Const BOOK_TABLE As String = "Book" Dim dSet As DataSet = Nothing Dim xmlFilename As String If (Not Page.IsPostBack) Then '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() End If End Sub 'Page_Load End Class 'CH02DataGridWithXMLVB End Namespace 

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

 using System; using System.Configuration; using System.Data; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02DataGridWithXMLCS.aspx /// </summary> public partial class CH02DataGridWithXMLCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { const String BOOK_TABLE = "Book"; DataSet dSet = null; String xmlFilename; if (!Page.IsPostBack) { // 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(); } } // Page_Load } // CH02DataGridWithXMLCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net