. NET Framework provides many methods to access and operate data, including XML. Reading the original web page data from an XML file is better than loading content from a database in many ways. You can easily build XML documents and generate them from databases or other data sources. You can divide the data into small, easy-to-transfer parts, and you can use XML for free without restrictions.
I will use an example program to explain how to display dynamic content on your Web page by using an XML file as a data source and binding it to the ASP. NET DataList control.
|
| Figure 1. Manage page content in XML file |
Sample programReference part of the index in my Getting Started column as data. On the articles. aspx page, use the DataList control to display the article list. Each entry contains four lines of content. The first line shows the article title and Technology Toolbox linked to an online article. The second row contains the magazine, column type, and publication date. The third line is a brief overview of this article, and the last line contains a link to provide code download. This link returns a page with QueryString parameters, allowing you to record the page and file download requests.
This data represents the structure of the XML document located in a Web server, which is a small part of the sample document ):
The element is repeated in each article listed in this file.
You can read an XML file into a DataSet object of ADO. NET, which is the data source of the DataList control you specified.
You can use the following methods. NET Framework to load XML files. This mainly depends on the complexity of your data and how you want to display it. You can view ADO. NET documentation to learn more about this ). The simplest method is to use the ReadXML method of the DataSet object:
Dim ds As New DataSet ds.ReadXml("c:\inetpub\demoflat.xml") |
If you have an XML schema (XSD) file, you can use the ReadXmlSchema method of DataSet to load it. However, by default, the ReadXml method will deduce a schema from the input file. To pass demoflat. xml to the ReadXml method,Article. Is the top element in the XML data structure, which is located under the root element.
Study XML structure in DataSet
You can easily study the XML data structure by displaying it to a DataGrid Control in ASP. NET Web form. Drag a DataGrid control from the Web Forms bar of the VS. NET toolkit to the WebForm1 design interface. In the Page_Load event of the form, add the following code and double-click the WebForm1 design interface to enter the code section ):
Dim dsFlat As New DataSet() Dim sXmlPath As String = _ " c:\inetpub\demoflat.xml" dsFlat.ReadXml(sXmlPath) With DataGrid1 .DataSource = dsFlat.Tables("article") .DataBind() End With |
The ReadXml method is used to load XML content to dsFlat DataSet. You can set the DataSource attribute of the DataGrid to article table in DataSet, and then call DataBind to implement the connection. This is the simplest Data Binding in ASP. NET. You will immediately see its powerful functions.
When running this project, you will see that each parameter of the article element has a column, and each article has a line. With this structure, you can display the question of the article as a link. The QueryString parameter of the URL comes from Element value. For example, the URL of an article looks like this:
This looks good, but the data is just a simple row-column structure. You may want to specify the text to a link or multiple links. Therefore, the demohier. xml file adds Element:
The element has its own attribute. It represents the second table in DataSet. Codeurl.
Binding data to hierarchies is troublesome. You need to modify the page to display the demohier. xml data in two additional DataGrid. When running this page, you will see that ADO. NET has created a link column named article_id in the article and codeurl tables to represent the parent and child elements respectively. For more information, see Figure 2).
|
| Figure 2. Understand the XML Data hierarchy |
Now you can focus on the main events of this column-build this form with a DataList binding that displays the document directory data of the articles. xml file. Right-click the articles. aspx project in Solution Explorer (SE), and select Set as Start Page in the pop-up menu. Drag your styles.css project from Seto the articles. aspx design interface to include stylesheet.
Next, drag a DataList control from the toolbox to the design interface, and set its ID attribute to dlsArticles. A gray rectangle in the design interface represents DataList. Right-click the rectangle and select Edit Template | Item Templates from the context menu. Drag the Hyperlink control from the toolbox to the Item Template text box in the Item Templates design interface. Set the Control ID to hypTitle, and then empty the Text attribute.
Now, drag a Label control to the Project template with the ID value lblTech and press Enter to move down a row. Drag three Label controls in the new row: lblPub, lblType, and lblDate; then press Enter to move to the third row, drag a Label control lblDescription; then press Enter to move to the fourth row, drag a hypDownload link. Right-click the design page of Item Templates and select End Template Editing.
Some mandatory Assembly
Next, you must perform some manual operations to improve the default appearance of the controls in DataList. Click the HTML tag in the lower-left corner of the page design window to view the HTML code of the page.
And
Section) label with a simple
Separator) to shorten the vertical distance between controls. After formatting the style of each control, you can edit the Header, Footer, and Separator templates at will.
After you have written some code to complete this task, you will return to the Data Binding task of the template control of this project. Double-click the design page to see the code below. Insert the following lines of code at the top of articles. aspx. vb on the class declaration page:
Imports System.Data.OleDb Imports System.Xml Imports System.Configuration _ .ConfigurationSettings |
Insert these statements above the "Web Form Designer Generated Code" area:
Private mDS As New DataSet() Private msXmlPath As String |
Double-click in SE and open the project's web. config file. It is an XML file ), Enter these lines of code below the root element to set the location of the XML file:
This relative path specifies that the articles. xml file will be located in a content directory under the Web root directory of your project.
During the page_load event, insert the following code to get the location of the XML file and display the page:
msXmlPath = Server.MapPath _ (AppSettings.Get("XmlPath")) DisplayArticleData() |
Next, add the DisplayArticleData program, which is used to fill the DataSet and combine it with the DataSource attribute bound to DataList:
Private Sub DisplayArticleData() mDS.ReadXml(msXmlPath) With dlsArticles .DataSource = _ mDS.Tables("article") .DataBind() End With End Sub |
In this way, the DataSet and DataList are connected, and the control is included. However, you must connect the data in the DataSet with a single template control. Return to the design page on the articles. aspx page, click the HTML tag, and declare the hypTitle control in ItemTemplate to bind the title data element to the link text:
<%# DataBinder.Eval (Container.DataItem, "title") %> |
The string contained in the <% # and %> separator is a "data binding expression ". One expression has two forms: one is to use the DataBinder object when executing the code, and the other will return data with functions as I will talk about soon ).
In the hypTitle control, the Eval method of the DataBinder object is used to obtain "title" DataItem from a current container object in DataList. This DataItem is obtained from the DataSet of the DataList you bound to DisplayArticleData. Remember that the first XML element in an article is title. The preceding complex expression simply sets the Text attribute of the hyperlink control to the value of the title field of the current record. a row of data in DataList is represented as a row in the table, the result is displayed as the title of a column of articles.
Use Data Binding to save time
Once you understand how to use data binding, you will find that it will generate tables for you to display data, so that you can write a lot of code from the work as in the traditional ASP). In ASP. NET, you can spend more time designing the appearance of the page, rather than writing code for data access.
When running this project, you should view the Title List of the article. Other DataList controls do not display any data, because you have not bound them to DataSource. The Label control of DataList is intuitive. It displays each special field bound to DataSet:
<%# DataBinder.Eval (Container.DataItem,"description")%> |
The hypTitle Hyperlink control uses the second data binding expression. It uses a function to return data used for the navigateurl attribute:
navigateurl='<%# GetArticleUrl (DataBinder.Eval(Container.DataItem, "readurl")) %>' |
The GetArticleUr function takes the readurl value from the current row of the original DataSet, takes it as a parameter, and returns a URL with the QueryString parameter, which is used to return the previous page:
Protected Function GetArticleUrl _ (ByVal LinkID As String) As String Return "articles.aspx?ID=" & LinkID End Function |
It is more interesting to bind data using the hypDownload control because it uses data from multiple tables in the input DataSet. The GetCodeUrl and GetCodeUrlText functions are used to return a URL and the text used for the link respectively. For details, seeList 1):
'> <%# GetCodeUrlText(DataBinder.Eval (Container.DataItem,"article_id"))%> |
Note: use single quotes instead of double quotes in the value of the navigateurl parameter ). This is necessary because double quotation marks will appear in the data binding expression. ASP. NET Correctly interprets single quotes.
It is responsible for data binding tasks. Return to the page_load event, check the QueryString ID parameter, and call any DisplayArticleData to display the page if there is no parameter), or call LogAndDisplayLink when the article or code link is required:
Dim sID As String = _ Request.QueryString("ID") If sID.Length > 0 Then LogAndDisplayLink(sID) Else DisplayArticleData() End If |
The LogAndDisplayLink program records requests as expected, searches for URLs in the XML Link Table Based on the ID, and redirects the page request:
'log request here ... mDS.ReadXml(msXmlPath) Dim dv As DataView = _ mDS.Tables("link").DefaultView dv.RowFilter = "id='" & LinkID & "'" Dim sURL As String = dv.Item(0).Item(1) Response.Redirect(sURL) |
With the help of the DataView object, you can implement a chain table. You can set the RowFilter attribute of DataView to search for the project from the chain table. Its ID is transmitted to the QueryString parameter of the page. You can read the results from dv. item (0). item (1). item (0) indicates the row, and item (1) indicates the column. When you click a link, a new page is displayed and the required content is displayed.
It is very easy to use XML files as data sources, which enables you to use a database to dynamically display Web content. The combination of ASP. NET data binding and XML data sources enables you to put data on a Web page with a minimum amount of code. However, when your XML data has a hierarchical structure, the Data Binding task becomes more complex. In some cases, you have to weigh between complex data and the inability to display data on Web pages.