ASP. Walkthrough: Creating a Web page to display XML data

Source: Internet
Author: User
Tags xsl xsl file xslt

Data is typically provided to the WEB application in XML format. However, XML data is inherently hierarchical, so you might want to be able to use XML data, such as a GridView or DropDownList control, in a list-based control. This walkthrough demonstrates how to treat XML data as data in a tabular database table.

With this walkthrough, you will learn how to perform the following tasks:

• Use the data source control to read the XML data and provide the data to the list control.

• Bind the GridView and DataList controls to XML data.

• Create a Master detail page that displays logical-related XML data.

• Apply a transform to the. xml file to make the file available as tabular data.

I. Create a website

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 the site and go to the next section. Otherwise, follow the steps below to create a new Web site and Web page. To create a file system Web site:

1. Open the 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.

4 in the Location box, click File System, and then enter the name of the folder where you want to save the Web site. For example, type the folder name "C:/websites/xmlwalkthrough".

5. In the Language list, click the programming language you want to use, such as visual Basic or Visual C #. The programming language you choose will be the default language for your Web site, but you can set the programming language separately for each page.

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

Ii. creating an. xml file for data

To use XML data, create an. xml file in your Web site.

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

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

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

3. Type "Bookstore.xml" in the "Name" box.

4. Click "Add". A new. xml file that contains only XML directives is created.

5. Copy the following XML data and paste it into a file to overwrite the contents of 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 the World Literature"

Price= "24.95" >

<comments>

<usercomment rating= "3"

Comment= "Needs more modern literature."/>

<usercomment rating= "4"

Comment= "Excellent overview of the 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 may be available on the online bookstore. Please note the following features of the. xml file:

• The attribute value of the element is represented as a property (Attribute).

• The file contains a nested structure-each book can contain a book's attribute values, and one or more comments as separate elements.

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

Iii. displaying XML data in a list control

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

3.1. Configure data access to the. xml file

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

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

3. In the XmlDataSource Task 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 the controls in the page. This data can be used in two formats: hierarchical format and tabular format. Controls that are bound to XmlDataSource controls can get the data in their appropriate format.

In this case, the hierarchical structure of the Bookstore.xml file helps to interpret the relationship. The two levels (books and notes) of a file are visible as two related tables.

You can now display XML data in a list control. At the beginning, you can display some XML data in the GridView control.

3.2. Use the GridView control as the basic display tool for XML data

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

2. On the GridView Task menu, in the Select Data Source list, click XmlDataSource1.

3. Press CTRL+F5 to run the page.

The page displays the XML data in the grid. The data that is displayed in the GridView control demonstrates the following points about how to interpret the XML data:

• If the XML data is represented as a data record, by default, the columns are created from properties such as ISBN.

• Child elements are considered to be part of a separate related table. In this example, the GridView control is not bound to the comments element in the file.

Iv. filtering XML data using an XPath expression

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

In this part of the walkthrough, you will add another GridView control and use the control to display the master/detail information. The user will be able to select a book in the first GridView control, and the second GridView control will display the relevant user comments for that book, if any. To display comments, you need to use an XPath expression that allows you to specify the level of the XML data file to extract. Because you want to display only comments for a particular book, the XPath expression is created dynamically, depending on the book selected by the user.

At the beginning, add another GridView control to the page, and then configure the GridView control so that it displays user comments.

4.1. Add GridView control to display user comments

1. Switch to "design" view.

2. In the Toolbox, from the Data group, drag the GridView control onto the page and place it under the first GridView control. The GridView task menu appears.

3. In the Select 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 ID for data source box, leave the default value of "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. xml file that you have used in this walkthrough, but you will extract different information from the file 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 properties dynamically in your code. However, by defining an XPath expression for the data source, the tools in Visual Web Designer are now helping to determine the information that is ultimately displayed in the control.

9. Click OK. A second GridView control appears, showing the ratings and user comments as sample data.

10. Select the "GridView2" control and set "visible" to "False" in properties. The second GridView control is displayed only when the user selects a book in the first GridView control.

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

4.2. Configure the GridView control for the selected content

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

2. In the GridView task menu, select Enable Selection. A new column is added to the GridView control, which contains a link button whose text is select.

3. In properties, set "DataKeyNames" to "ISBN". You can click the property box to select the value. After the GridView control is configured like this, the ISBN property is treated 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. All events associated with the control are displayed.

5. Double-click the box for the "SelectedIndexChanged" event. You can switch to the Code Editor and create a skeleton handler for the SelectedIndexChanged event.

6. Add the following highlighted code to the handler.

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;

}

This code performs the following actions:

• Use the SelectedIndex property (which belongs to the GridView control) to index the array of data keys and return the primary key for the selected row. Previously, the DataKeyNames property was set to include the ISBN number.

• Create a new XPath expression that contains the selected ISBN.

• Assign this new XPath expression to an XPath property (belonging to the XmlDataSource2 control). Assigning a new XPath expression to an XPath property causes the XmlDataSource control to recalculate its return data. The GridView control is then rebind to the data.

• Set the Visible property to True to display a second GridView control. When you create a second GridView control, the visibility is declaratively set to false so that the control is not displayed until the user selects the book.

You can now test the page.

4.3. Test the filter with an XPath expression

1. Review the Default.aspx page and press Ctrl+f5 to run the page. The page appears, where the information for the book is in the grid.

2. Click the "select" link next to the first book. The note for the book is displayed in the second grid.

3. Click the "select" link next to the last book. No comments are displayed because the book has no comments.

V. Using a custom layout to display XML data

To create a custom layout for data, you can use the DataList control. In the DataList control, you can define one or more templates. Each template contains static text and a combination of several controls, where the layout of the text and controls can be arranged arbitrarily.

In this part of the walkthrough, you will use a DataList control to display the information that was originally displayed with the GridView2 control. However, you can create a custom layout for user comments.

5.1. Using a custom layout to display XML data

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 the DataList control onto the page.

3. On the DataList Task menu, in select a Data source list, click XmlDataSource2. The data source for the GRIDVIEW2 control will be used for the DataList control.

4. In properties, set visible to false.

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

6. In the DataList task menu, click Edit Template, and then click Item Template in the Show box. The DataList control appears with an editable region for the item template. The template contains a default layout consisting of static text and Label controls that are bound to the Rating and Comment columns in the data record. (The DataList control can infer the data structure it will display because a static XPath expression was defined for the XmlDataSource2 control earlier in this walkthrough.) )

7. In the editable region, change the first title to user rating:.

8. Change the title "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, which defines the layout of the elements that will be displayed between each data record.

10. In the Toolbox, drag the horizontal ruler control from the HTML group to the editable region.

11. Right-click the "DataList" control, then "End Template Edit".

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

13. In the "gridview1_selectedindexchanged" handler, change the following line:

Gridview2.visible = true; Change to the following: Datalist1.visible = true;

5.2. Test the custom layout

1. Review the Default.aspx page and press Ctrl+f5 to run the page. The page appears, where the information for the book is in the grid.

2. Click the "select" link next to the first book. The comments in the first book are displayed in the list.

3. Click the "select" link next to the last book. No comments are displayed because the book has no comments.

Vi. using transformations to refactor XML data

The. xml file used in this walkthrough is structured so that each element's attribute (property) is represented as a property (Attribute). In many cases, the. xml files that are used are structurally completely different. For example, the values in the. xml file are typically created as elements that have internal text.

If the property value in the. xml file is not represented as an attribute (Attribute) format, you can create a transform file (. xslt) that can dynamically reformat the. xml file to make it compatible with the XmlDataSource control.

In this part of the walkthrough, you will use an. xml file that contains the same data as the data in the Bookstore.xml file that you used earlier. However, the structure of the data differs from the structure in the Bookstore.xml. xml file, so you need to use transformations to dynamically reformat the data.

At the beginning, another. xml file is created.

6.1. Create a second. xml file

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

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

3. Type "Bookstore2.xml" in the "Name" box.

4. Click "Add". A new. xml file that contains only XML directives is created.

5. Copy the following XML data and paste it into a file to overwrite the contents of 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 the 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 transform file to convert the data in the Bookstore2.xml file to the attribute-based format used by the XmlDataSource control.

6.2. Create a transform file

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

2. Under Visual Studio installed templates, click Text File. No file templates are converted, so you can create them by creating a text file with the correct extension.

3. Type "bookstore2.xsl" in the "Name" box. Description: Be sure to use the. xsl extension.

4. Click "Add". A new, blank file is created.

5. Copy the following conversion 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 now on, you can work with XML data in a manner similar to the previous part of this walkthrough, except that you can specify the transform file when you configure the XmlDataSource control. In the last part of this walkthrough, you will create a new page and then repeat some of the steps in the first part of this walkthrough. However, this time the data in the Bookstore2.xml file is displayed.

6.3. Configure data access to the. xml file

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

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

3. Type "bookstore2.aspx" in the "Name" box.

4. Click "Add".

5. Switch to "design" view.

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

7. In the XmlDataSource Task menu, click Configure Data source. The Configure Data Source dialog box appears.

8. In the Data File box, type "~/app_data/bookstore2.xml".

9. In the Convert File box, type ~/app_data/bookstore2.xsl.

10. Click OK.

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

12. On the GridView Task menu, in the Select Data Source list, click XmlDataSource1.

13. Press CTRL+F5 to run the page. The page displays the XML data in the grid. As before, the data will appear in the grid on the first page, even if the underlying. xml file is in a different format.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.