Sdílet prostřednictvím


Walkthrough: Creating a Web Page to Display XML Data

Data is often made available to Web applications in XML format. However, XML data is inherently hierarchical, and you might want to be able to use the XML data in list-based controls, such as the GridView or DropDownList control. This walkthrough shows you how to work with XML data as if it were in a tabular database table.

During this walkthrough, you will learn how to:

  • Use a data source control to read XML data and make it available to list controls.

  • Bind the GridView and DataList controls to XML data.

  • Create a master-detail page that displays logically related XML data.

  • Apply a transformation to an .xml file to make the file usable as tabular data.

Note

You can also work with XML in hierarchical form. For details, see Walkthrough: Displaying Hierarchical Data in a TreeView Control.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Web Developer

  • The .NET Framework

This walkthrough assumes that you know how to use Visual Web Developer.

Creating a Web Site

If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section. Otherwise, create a new Web site and page by following these steps.

To create a file system Web site

  1. Open Visual Web Developer.

  2. On the File menu, point to New Web Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. In the Location box, click File System, and then enter the name of the folder where you want to keep your Web site.

    For example, type the folder name C:\WebSites\XMLWalkthrough.

  5. In the Language list, click the programming language you prefer to work in, such as Visual Basic or Visual C#.

    The programming language you choose will be the default for your Web site, but you can set the programming language for each page individually.

  6. Click OK.

    Visual Web Developer creates the folder and a new page named Default.aspx.

Creating an .xml file for Data

To have XML data to work with, create an .xml file in the Web site.

To create the .xml file

  1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.

    Note

    When you put the .xml file in the App_Data folder, the .xml file has the correct permissions to allow ASP.NET to read from and write to the file at run time. In addition, keeping files in the App_Data folder protects them from being viewed in a browser, because the App_Data folder is marked as non-browsable.

  2. Under Visual Studio installed templates, click XML file.

  3. In the Name box, type Bookstore.xml.

  4. Click Add.

    A new .xml file is created containing only the XML directive.

  5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.

    <?xml version="1.0" standalone="yes"?>
    <bookstore>
        <book ISBN="10-000000-001" 
            title="The Iliad and The Odyssey" 
            price="12.95">
        <comments>
            <userComment rating="4" 
                comment="Best translation I've read." />
            <userComment rating="2" 
                comment="I like other versions better." />
          </comments>
       </book>
       <book ISBN="10-000000-999" 
            title="Anthology of World Literature" 
            price="24.95">
       <comments>
          <userComment rating="3" 
              comment="Needs more modern literature." />
          <userComment rating="4" 
              comment="Excellent overview of world literature." />
       </comments>
       </book>
        <book ISBN="11-000000-002" 
            title="Computer Dictionary" 
            price="24.95" >
          <comments>
             <userComment rating="3" 
                 comment="A valuable resource." />
          </comments>
       </book>
        <book ISBN="11-000000-003" 
            title="Cooking on a Budget" 
            price="23.95" >
       <comments>
          <userComment rating="4" 
              comment="Delicious!" />
        </comments>
        </book>
        <book ISBN="11-000000-004" 
            title="Great Works of Art" 
            price="29.95" >
       </book>
    </bookstore>
    

    The Bookstore.xml file contains information about books that might be available from an online bookstore. Notice the following about the .xml file:

    • The property values for elements are all expressed as attributes.

    • The file contains a nested structure — each book can contain its property values, as well as one or more comments as separate elements.

  6. Save the Bookstore.xml file, and then close it.

Displaying XML Data in a List Control

To make data available to the controls on an ASP.NET Web page, you use a data source control.

To configure data access to the .xml file

  1. Open the Default.aspx file, and then switch to Design view.

  2. In the Toolbox, from the Data group, drag an XmlDataSource control onto the page.

  3. On the XmlDataSource Tasks menu, click Configure Data Source.

    The Configure Data Source <DataSourceName> dialog box appears.

  4. In the Data file box, type ~/App_Data/Bookstore.xml.

  5. Click OK.

The XmlDataSource control makes the data in the .xml file available to controls that are on the page. The data is available in two formats: hierarchical and tabular. Controls that bind to the XmlDataSource control can get the data in the format that works for them.

In this case, the hierarchy of the Bookstore.xml file lends itself to a relational interpretation. The two levels of the file (books and comments) can be thought of as two related tables.

You can now display the XML data in a list control. To begin, display some of the XML data in a GridView control.

To use a GridView control for basic display of XML data

  1. In the Toolbox, from the Data group, drag a GridView control onto the page.

  2. On the GridView Tasks menu, in the Choose Data Source list, click XmlDataSource1.

  3. Press CTRL+F5 to run the page.

    The page displays the XML data in a grid.

The data displayed in the GridView control illustrates the following points about how the XML data is interpreted:

  • When the XML data is represented as a data record, by default, the columns are created from attributes (such as ISBN).

  • Child elements are treated as part of a separate related table. For this example, the GridView control does not bind to the comments elements in the file.

Filtering XML Data Using an XPath Expression

In the first part of this walkthrough, you relied on the default behavior of the XmlDataSource and GridView controls to extract information from the .xml file. However, the control displays only some of the XML data.

In this part of the walkthrough, you will add a second GridView control and use it to show master-detail information. Users will be able to select an individual book in the first GridView control, and the second GridView control will display the related user comments, if any, for that book. To display comments, you will use an XPath expression, which allows you to specify which level of the XML data file you want to extract. Because you want to display comments for a specific book only, you will create the XPath expression dynamically, depending on which book the user has selected.

To begin, you will add a second GridView control to the page, and then configure the GridView control so that it will display user comments.

To add a GridView control to display user comments

  1. Switch to Design view.

  2. In the Toolbox, from the Data group, drag a GridView control onto the page and place it below the first GridView control.

    The GridView Tasks menu appears.

  3. In the Choose Data Source box, click New data source.

    The Data Source Configuration Wizard appears.

  4. Click XML File as the data source.

  5. In the Specify an ID for the data source box, leave the default, XmlDataSource2.

  6. Click OK.

    The Configure Data Source dialog box appears.

  7. In the Data file box, type ~/App_Data/Bookstore.xml.

    You will use the same .xml file that you used previously in this walkthrough, but you will extract different information from it for the second GridView control.

  8. In the XPath Expression box, type the following expression:

    /bookstore/book/comments/userComment

    Later, you will change the XPath property dynamically in code. However, by defining an XPath expression for the data source now, you will help the tools in Visual Web Designer determine what information will ultimately be displayed in the control.

  9. Click OK.

    The second GridView control appears, showing ratings and user comments as sample data.

  10. Select the GridView2 control, and in Properties, set Visible to False.

    The second GridView control will appear only when the user has selected a book in the first GridView control.

You can now configure the first GridView control to allow users to select a book. You will also add code that creates an XPath expression based on the user's selection and assigns it to the XmlDataSource2 control. The end result is that the second GridView control will display the user comments for the selected book.

To configure the GridView control for selection

  1. Switch to Design view, and then select the first GridView control.

  2. On the GridView Tasks menu, select Enable Selection.

    A new column is added to the GridView control containing a link button with the text Select.

  3. In Properties, set DataKeyNames to ISBN.

    You can click the property box to select the value.

    This configures the GridView control to treat the ISBN property as the primary key for each element in the XML data.

  4. Click the GridView control. In the Properties window, select Events from the drop-down list at the top of the Properties window. This will display all events associated with the control.

  5. Double-click the box for the SelectedIndexChanged event.

    This switches you to the code editor and creates a skeleton handler for the SelectedIndexChanged event.

  6. Add the following highlighted code to the handler.

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles GridView1.SelectedIndexChanged
            Dim currentIndex As Integer        currentIndex = GridView1.SelectedIndex        Dim isbn As String        isbn = CStr(GridView1.DataKeys(currentIndex).Value)        XmlDataSource2.XPath = _            String.Format( _            "/bookstore/book[@ISBN='{0}']/comments/userComment", _            isbn)        GridView2.Visible = true
    End Sub
    
    protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
    {
        String isbn = (String)         GridView1.DataKeys[GridView1.SelectedIndex].Value;        XmlDataSource2.XPath =             String.Format(              "/bookstore/book[@ISBN='{0}']/comments/userComment",             isbn);        GridView2.Visible = true;
    }
    

    The code does the following:

    • It uses the SelectedIndex property (of the GridView control) to index into the array of data keys, and then return the primary key of the selected row. Previously, you set the DataKeyNames property to contain ISBN numbers.

    • It creates a new XPath expression that includes the selected ISBN.

    • It assigns the new XPath expression to the XPath property (of the XmlDataSource2 control). Assigning a new XPath expression to the XPath property causes the XmlDataSource control to re-evaluate the data it returns. The GridView control, in turn, rebinds to the data.

    • It sets the Visible property to true, which causes the second GridView control to be displayed. You declaratively set the visibility to false when you created the second GridView control so that it does not appear until the user selects a book.

You can now test the page.

To test filtering with the XPath expression

  1. View the Default.aspx page and press CTRL+F5 to run the page.

    The page is displayed with a grid of information about books.

  2. Click the Select link next to the first book.

    The comments about that book are displayed in a second grid.

  3. Click the Select link next to the last book.

    No comments are displayed, because there are none for this book.

Displaying XML Data with a Custom Layout

To create a custom layout for data, you can use a DataList control. In the DataList control, you can define one or more templates. Each template contains a combination of static text and controls that you can arrange in any layout you want.

In this part of the walkthrough, you will use a DataList control to display the same information that you previously displayed using the GridView2 control. However, you will be able to create a custom layout for the user comments.

To display XML data with a custom layout

  1. Switch to Design view, click the GridView2 control, and then press DELETE to remove it from the page.

  2. In the Toolbox, from the Data group, drag a DataList control onto the page.

  3. On the DataList Tasks menu, in the Choose Data Source list, click XmlDataSource2.

    You will use the same data source for the DataList control that you used for the GridView2 control.

  4. In Properties, set Visible to false.

  5. If the smart tag does not appear, right-click the DataList control and then click Show Smart Tag.

  6. On the DataList Tasks menu, click Edit Templates, and then in the Display box, click Item Template.

    The DataList control appears with an editable region for the item template. The template contains a default layout that consists of static text and Label controls that are bound to the Rating and Comment columns in the data record. (The DataList control is able to infer the structure of the data that it will display because you defined a static XPath expression for the XmlDataSource2 control earlier in this walkthrough.)

  7. In the editable region, change the first caption to User rating:.

  8. Change the caption comment to Comment:.

  9. Right-click the title bar of the DataList control, point to Edit Template, and then click Separator Template.

    Another editable region is displayed in the DataList control, this one for defining the layout of the elements that will appear between each data record.

  10. In the Toolbox, from the HTML group, drag a Horizontal Rule control onto the editable region.

  11. Right-click the DataList control, and then click End Template Editing.

  12. Right-click the page, and then click View Code to switch to the code for the page.

  13. In the GridView1_SelectedIndexChanged handler, change the following line:

    GridView2.Visible = True
    
    GridView2.Visible = true;
    

    to the following:

    DataList1.Visible = True
    
    DataList1.Visible = true;
    

You can now test the custom layout.

To test the custom layout

  1. View the Default.aspx page and press CTRL+F5 to run the page.

    The page is displayed with a grid of information about books.

  2. Click the Select link next to the first book.

    The comments about the first book are displayed in a list.

  3. Click the Select link next to the last book.

    No comments are displayed, because there are none for this book.

Using Transformations to Restructure XML Data

The .xml file that you have used in this walkthrough is structured so that the properties of each element are expressed as attributes. In many cases, .xml files that you work with are structured differently. For example, values in an .xml file are often created as elements with inner text.

If you have an .xml file in which property values are expressed in a format other than attributes, you can create a transformation file (.xslt) that can dynamically reformat the .xml file so that it is compatible with the XmlDataSource control.

In this part of the walkthrough, you will work with an .xml file that contains the same data as the Bookstore.xml file that you used previously. However, the data will be structured differently than it was in the Bookstore.xml file, so you will use a transformation to dynamically reformat it.

To begin this section, you will create a second .xml file.

To create the second .xml file

  1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.

  2. Under Visual Studio installed templates, click XML file.

  3. In the Name box, type Bookstore2.xml.

  4. Click Add.

    A new .xml file is created containing only the XML directive.

  5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.

    <?xml version="1.0" standalone="yes"?>
    <bookstore>
        <book ISBN="10-000000-001">
            <title>The Iliad and The Odyssey</title>
            <price>12.95</price>
            <comments>
                <userComment rating="4">
                    Best translation I've read.
                </userComment>
                <userComment rating="2">
                    I like other versions better.
                </userComment>
            </comments>
        </book>
        <book ISBN="10-000000-999">
            <title>Anthology of World Literature</title>
            <price>24.95</price>
            <comments>
                <userComment rating="3">
                    Needs more modern literature.
                </userComment>
                <userComment rating="4">
                    Excellent overview of world literature.
                </userComment>
            </comments>
        </book>
        <book ISBN="11-000000-002">
            <title>Computer Dictionary</title>
            <price>24.95</price>
            <comments>
                <userComment rating="3">
                   A valuable resource.
                </userComment>
            </comments>
        </book>
        <book ISBN="11-000000-003">
            <title>Cooking on a Budget</title>
            <price>23.95</price>
            <comments>
                <userComment rating="4">Delicious!</userComment>
            </comments>
        </book>
        <book ISBN="11-000000-004">
            <title>Great Works of Art</title>
            <price>29.95</price>
        </book>
    </bookstore>
    
  6. Save the Bookstore2.xml file, and then close it.

You now need a transformation file that will convert the data in the Bookstore2.xml file into the attribute-based format that is used by the XmlDataSource control.

To create the transformation file

  1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.

  2. Under Visual Studio installed templates, click Text File.

    There is no template for a transform file, so you can create it as a text file with the correct extension.

  3. In the Name box, type Bookstore2.xsl.

    Note

    Be sure to use the .xsl extension.

  4. Click Add.

    A new blank file is created.

  5. Copy the following transformation code, and then paste it into the file.

    <?xml version="1.0"?>
    <xsl:stylesheet 
       version="1.0"
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    >
       <xsl:strip-space elements="*"/>
       <xsl:output method="xml" 
           omit-xml-declaration="yes" 
           indent="yes" 
           standalone="yes" />
    
       <xsl:template match="/">
          <xsl:for-each select="bookstore">
             <xsl:element name="bookstore">
                <xsl:for-each select="book">
                   <xsl:element name="book">
                      <xsl:attribute name="ISBN">
                         <xsl:value-of select="@ISBN"/>
                      </xsl:attribute>
                      <xsl:attribute name="title">
                         <xsl:value-of select="title"/>
                      </xsl:attribute>
                      <xsl:attribute name="price">
                         <xsl:value-of select="price"/>
                      </xsl:attribute>
                   </xsl:element>
                </xsl:for-each>
             </xsl:element>
          </xsl:for-each>
       </xsl:template>
    </xsl:stylesheet>
    
  6. Save the Bookstore2.xsl file, and then close it.

From this point, working with the XML data is very similar to what you did earlier in this walkthrough, except that you can specify the transformation file when you configure the XmlDataSource control. For the last part of this walkthrough, you will create a new page, and then repeat some of the steps from the first part of this walkthrough. However, this time you will show the data from the Bookstore2.xml file.

To configure data access to the .xml file

  1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.

  2. Under Visual Studio installed templates, click Web Form.

  3. In the Name box, type Bookstore2.aspx.

  4. Click Add.

  5. Switch to Design view.

  6. In the Toolbox, from the Data group, drag an XmlDataSource control onto the page.

  7. On the XmlDataSource Tasks menu, click Configure Data Source.

    The Configure Data Source dialog boxappears.

  8. In the Data file box, type ~/App_Data/Bookstore2.xml.

  9. In the Transform file box, type ~/App_Data/Bookstore2.xsl.

  10. Click OK.

  11. In the Toolbox, from the Data group, drag a GridView control onto the page.

  12. On the GridView Tasks menu, in the Choose Data Source list, click XmlDataSource1.

  13. Press CTRL+F5 to run the page.

    The page displays the XML data in a grid. The data will appear in the grid the same as it did in the first page, even though the format of the underlying .xml file is different this time.

Next Steps

This walkthrough has illustrated only the basics of how to work with an XML document and transformations. In a real application, you will often need to work with the XML document in more depth. The following are suggestions for further investigation:

  • Creating more sophisticated transformations. In this walkthrough, you have seen only one example of how you can use transformations. XSL is a powerful language, with sophisticated support not just for creating HTML pages, but also for virtually any kind of transformation from XML to another structure.

  • Writing XML documents (instead of simply reading them). The Xml control makes it easy to display the contents of an XML file in an ASP.NET Web page. However, you might want to create or amend XML files yourself. For details, see XML Documents and Data. For an example of writing to an XML file, see Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control.

See Also

Tasks

Walkthrough: Displaying Hierarchical Data in a TreeView Control

Walkthrough: Creating a Basic Web Page in Visual Web Developer