Using Dynamic Interfaces with XML

You can separate data by format by using an XML document to provide the data and an XSLT document to describe the layout. (Recall that XML is eXtended Markup Language and XSLT is XML Style Transform . XSLT is like a cascading style sheet for XML.) Combined with caching and caching dependencies, you can provide users with a custom view of the data separated from the data, needing to render a new page only if some external dependency changes. For example, you could provide users with an order status view, updating the rendered page only when the order status has been updated.

We'll look at each part of XML data, XSL Transform documents, and caching dependencies in the subsections that follow, bringing it all together at the end.

Using XML Data

Using XML data and XSL Transform documents is pretty easy in .NET because there is an Xml control on the Web Forms tab of the Toolbox. The Xml control has DocumentSource and TransformSource properties that provide you with a way to indicate the XML source of the data and the file containing the XSL Transform document you want to use to describe the data. As a benefit, you can change the source of the data or the source of the transform and have the new data or presentation offered to your users. This occurs independently of the other file.

Suppose for the sake of demonstration that you are tasked with providing a daily order report for your boss. Your boss prefers to review the report at the end of the day on the train home from Manhattan to Scarsdale. Your boss doesn't want to carry paper, nor does she want to have to try to figure out the data on her cell phone. Finally, every couple of months she wants the report presented in a new format. You decide that this is a perfect scenario for implementing a simple XML export you can e-mail to your boss before she undocks her PC for the evening.


You don't need an elaborate scenario to justify using XML and XSLT. It is a good strategy to separate data from format, just as you would do with a Web page and a cascading style sheet. I was just having a bit of fun.

You probably wouldn't create the XML document by hand, but you could do so with a simple text editor like Notepad. We will assume you implemented some automated export process, saving the data to XML. Listing 15.28 contains the text for the XML document followed by a brief description of its contents and nature.

Listing 15.28 A Well-Formed XML Document Containing Only Self-Describing Data
 <?xml version="1.0" encoding="utf-8" ?> <orders xmlns:HTML="">   <product id="Instant Cup Noodles">     <units>105</units>     <revenue>10000</revenue>   </product>   <product id="Coffee Beans">     <units>100000</units>     <revenue>1000000</revenue>   </product>   <product id="Staples">     <units>25000</units>     <revenue>10000</revenue>   </product> </orders> 

Extensibility (the X in XML ) is a fancy way of saying that the document describes its contents. The first statement indicates that this document uses XML encoding. The second statement describes the contents of the document and an XML namespace. This document contains orders and is unique to other orders not in the namespace. The orders document describes volume and gross revenue by product. Each product tag represents a unique instance of a product with units and revenue properties.

By itself the data would be hard to read and perhaps daunting to an average reader. To alleviate this problem we can associate the XML document with an XSLT document, formatting the data in a presentable way.

Implementing an XSL Transform Document

XSLT documents don't add content to XML; rather, XSLT documents transform how the data is presented. XSLT documents are similar in nature to cascading style sheet documents in that they describe how things appear, but XSLT documents support the addition of selection and sorting criteria. As a result you can describe how the data is formatted and ordered as well as which data is actually displayed. For example, the XSLT document could exclude data even though the data was contained in the XML document.

For our purposes we want to select and display all the data. Listing 15.29 contains the text from the Orders.xslt document that is part of CachedDemo.sln . The XSLT simply describes the view of the document as an HTML table and dynamically selects and creates the HTML rows for the document.

Listing 15.29 An XSLT Document That Dynamically Creates an HTML Table
 1:  <xsl:stylesheet version="1.0" 2:   xmlns:xsl=""> 3:   <xsl:template match="/"> 4:      <table width="100%" border="1"> 5:        <tr> 6:          <th>Product</th> 7:          <th>Units</th> 8:          <th>Revenue</th> 9:       </tr> 10: 11:       <xsl:for-each select='orders/product'> 12:         <tr> 13:           <td> 14:             <xsl:value-of select='@id' /> 15:           </td> 16:           <td> 17:             <xsl:value-of select='units' /> 18:           </td> 19:           <td> 20:             <xsl:value-of select='revenue' /> 21:           </td> 22:         </tr> 23:       </xsl:for-each> 24:     </table> 25:   </xsl:template> 26: </xsl:stylesheet> 

XSLT documents can become quite elaborate. Listing 15.29 describes an HTML table and creates table rows and cells based on the number of product elements in the associated XML document.

Lines 1 and 2 describe the content of this document as an XSL style sheet. Lines 3 and 25 are the opening and matching closing <xsl:template> tags. The match attribute indicates the nodes that this template applies to. (You can look up the xsl:template element in the help documentation for complete information.) Lines 4 and 24 define an HTML table. The data will be displayed and organized in an HTML table. Lines 5 through 9 define a single, static, header row for the table. The header will always be displayed with the constant data.

The <xsl:for-each> tag works like a for loop in Visual Basic. Line 11 is understood to mean "repeat the HTML between lines 11 and 23 for each product in the XML document." Hence, we need to provide a template for only a single row and, regardless of the number of rows, we will get the correct HTML table description. Lines 14, 17, and 20 demonstrate how to obtain the value of a single product for each iteration of the for-each statement. We had three products in the Orders.xml document, so we will get three rows in the HTML table. Figure 15.20 shows the result.

Figure 15.20. The dynamically created and formatted HTML table as described by the XML and XSLT documents.



XML and XSLT are big subjects. You will be well served to acquire a couple of separate books on XML and XSLT.

To create the view shown in Figure 15.20, drop an Xml control on a Web page (or user control) from the Web Forms tab of the Toolbox. Assign the Xml.DocumentSource property to the Orders.xml file and the Xml. TransformSource to the Orders.xslt document. (If you are using your own data and transform files, substitute your files for the equivalent Orders files.)

Defining a Caching Dependency for an XSL-Formatted XML Document

So far so good. We have an XML document and a transform that describes the presentation of the document. Choosing a more elaborate presentation is a matter of experimentation. At this point we want to figure out how to reduce the number of times the XML and XSLT have to be read from the disk. By caching the XML and XSLT documents in the cache we can optimize our application. If we create a cache dependency, we can ensure that users get relevant data if the file data happens to change. The code for caching the XML document and transform source is identical, so I will demonstrate how to dynamically load, cache, and create a dependency on Orders.xml . (You can use the same technique for the XSLT file too.) Listing 15.30 demonstrates how to dynamically load the XML document and create a cache dependency so we can avoid reloading the data file unless it has changed.

Listing 15.30 Dynamically Loading an XML Document and Creating a Cache Dependency
 1:  Imports System.IO 2:  Imports System.Xml 3: 4:  Public Class WebForm1 5:      Inherits System.Web.UI.Page 6:      Protected WithEvents Xml1 As System.Web.UI.WebControls.Xml 7:      Protected WithEvents Label1 As System.Web.UI.WebControls.Label 8: 9:  [ Web Form Designer generated code ] 10: 11:   Private Sub Page_Load(ByVal sender As System.Object, _ 12:     ByVal e As System.EventArgs) Handles MyBase.Load 13: 14:     Label1.Text = String.Format("Cached was refreshed at: {0}", _ 15:       DateTime.Now) 16: 17:     If (Cache("Orders") Is Nothing) Then 18:       Dim Document As XmlDocument = New XmlDocument() 19:       If (File.Exists(Server.MapPath("~/Data/Orders.xml"))) Then 20:         Document.Load(Server.MapPath("~/Data/Orders.xml")) 21:         Context.Cache.Insert("Orders", Document, _ 22:           New Caching.CacheDependency( _ 23:           Server.MapPath("~/Data/Orders.xml"))) 24:       End If 25:     End If 26: 27:     Xml1.Document = CType(Cache("Orders"), XmlDocument) 28: 29: 30:   End Sub 31: 32: End Class 

The Page_Load event checks to determine whether the cache contains a value at the "Orders" key (line 17). If no such value exists, we create a new instance of an XmlDocument object (line 18). We verify that the physical XML file exists, load it into the XmlDocument object, and insert the XmlDocument object into the cache (lines 19 through 23.) The argument represented by the New Caching.CacheDependency object creates a dependency on the physical XML file. If the physical file is modified, the cache will be flushed.

Combining the @ OutputCache directive with the cache means that the page will be cached for the duration expressed and then rerendered when OutputCache expires . However, unless the XML file has been modified, the actual XML document will not be reloaded.

Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel © 2008-2017.
If you may any questions please contact us: