developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Promotional Products
Web Hosting Directory
Online Education
Imprinted Promotions
Corporate Awards
Promotional Gifts
Cell Phones
KVM over IP
PDA Phones & Cases
Memory
Corporate Gifts
Server Racks
Home Improvement
Online Shopping

 
Biz Resources
Ecommerce Hosting
Dedicated Server Hosting
Data Recovery Services


Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

An XML Guest Book Application
By Chris Eastwood

"By harnessing the power of XML, XSL and ASP, you can write Web applications in a snap. "

Most developers' first impression after reading about XML is "That sounds great, but what can I do with it?" The purpose of this article is to show how a little XML knowledge combined with Active Server Pages (ASP) and XSL can be used to create a guest book application for your Web site.

XML is a very powerful tool — you can use it for anything from a messaging system, to a back end database. The features I'm going to use in this article are based around the Microsoft XML Parser that shipped with the first release of Internet Explorer 5 (and will work on all future versions). This article assumes that you have at least a basic understanding of XML and ASP — I'll also be showing how you can use XSL from the Web server to ensure that all your clients can view the generated XML.

The guest book is a relatively simple feature of most Web sites. It can easily be broken down into an XML structure by analyzing the type of information you want to record from your visitors. Typically, a visitor to your site would leave the following information:

  • Visitor's Name
  • Visitor's Email Address
  • Visitor's Homepage
  • Visitor's Country
  • Message

We would also need to record the time and date that the message was left in the guest book — this is where we can take advantage of Active Server Pages to get the 'real' server time.

A typical XML document to record the above information could be:

<guestbook>
 <entry date="22/06/00 00:03:53">
   <name>Chris Eastwood</name>
   <email>chris@here.now</email>
   <homepage>http://www.vbcodelibrary.co.uk</homepage>
   <country>UK</country>
   <comment>This is the only comment in the guest book</comment>
 </entry>
</guestbook>

As you can see from the above example, we can record all of the information under each Entry node in the XML document. This is a very simple XML document and doesn't really need a Document Type Definition (DTD) to explain its structure. The document node 'guestbook' can hold multiple 'entry' nodes which will eventually make up the entire guest book.

Recording it All

Now that we know how we will be recording the guest book entries in an XML file, we need to investigate the mechanism that will allow us to record this data.

Figure 1 shows an example Guest Book form where the user would input their information.

Standard Web form used to gather guest book information

Most guest books are just a standard HTML Form that will post to a CGI script (or in our case, an ASP page). Our ASP page will take the input from a 'standard' HTML form and then create the XML objects on the server.

Our ASP page to retrieve the information from the HTML POST will perform the recording and storing of the data in the following steps:

  1. Retrieve the values from the HTML form
  2. Create a DOM object on the Server
  3. Load in the Existing Guest Book XML file (or create a new one)
  4. Create the relevant nodes in the XML file and populate them
  5. Save the XML file to the server

Retrieving the values from the HTML Form

  sName=Request("NAME")
  sEmail=Request("EMAIL")
  sHomePage=Request("HOMEPAGE")
  sCountry=Request("COUNTRY")
  sComment=Request("MESSAGE")

The above ASP code is quite straightforward, in that it just captures the variables from the HTTP header for use in the XML structure. You could place checks in this part of code to change any of the recorded data (filter out profanities, hide or 'munge' visitor email addresses, etc).

Create a DOM object on the Server/Load in the Existing Guest Book XML File

This code creates a page-level variable called oDOM that holds an instance of the Microsoft XMLDOM parser. We set its 'async' property to false (as we need it to parse before we can go to the next line of code). The oDOM object is then instructed to load in our guest book file — gbook.xml — from the server. If the XML file cannot be found then we simply create a new XML document with the LoadXML method on the oDOM object.

  Set oDOM = Server.CreateObject("Microsoft.XMLDOM")
  oDOM.async = false
  oDOM.load Server.MapPath("gbook.xml")
'
' Check if it wasn't found
'
  If oDOM.parseError.ErrorCode <> 0 Then ' not found! create an empty document
    oDOM.loadXML "<guestbook/>"
  End If

Create the relevant nodes in the XML file and populate them

This code creates a new 'entry' node in the XML document — this will form the 'root' for our guest book entry in the database. The setAttribute method on the node object will create the 'date' attribute of the node which records the time of the guest book entry

'
' Create an entry node in the guestbook XML document
'
  Set oEntryNode = oDOM.documentElement.AppendChild(oDOM.createElement("entry"))
  oEntryNode.setAttribute "date", now()

The following code then records each guest book entry field below the root entry node

'
' Create a 'name' node in the XML document
'
  Set oDetailsNode = oEntryNode.appendChild(oDOM.createElement("name"))
  oDetailsNode.Text = sName
'
' Create an 'email' node in the XML document
'
  Set oDetailsNode = oEntryNode.appendChild(oDOM.createElement("email"))
  oDetailsNode.Text = sEmail
'
' Create a 'homepage' node in the XML document
'
  Set oDetailsNode = oEntryNode.appendChild(oDOM.createElement("homepage"))
  oDetailsNode.Text = sHomePage
'
' Create a Country Node in the XML document
'
  Set oDetailsNode = oEntryNode.appendChild(oDOM.createElement("country"))
  oDetailsNode.Text = sCountry

Now that we have recorded all the visitor's information, we need to record the visitor's message. This message can be made up of multiple lines and we don't really want them putting HTML links into other files/sites so we create the comment node in the XML as a CDATA section:

'
' Create a 'Comment' Node in the XML Document - set it to be a 'cdata' section
'
  Set oDetailsNode = oEntryNode.appendChild(oDOM.createElement("comment"))
  oDetailsNode.appendChild oDOM.createCDATASection(sComment)

Now that we have built up the new nodes in the loaded XML file, we need to write it back to the web server's file system. This operation requires you to have write privileges in the XML documents directory on your ASP server  otherwise you will generate an ASP error:

  oDOM.Save Server.MapPath("gbook.xml")

That's it! We have now recorded the visitor's information and message inside an XML document stored on the Web server. The next step is to be able to show the guest book entries to other visitors.

Displaying the Guest Book Entries

One day, all Internet browsers will allow us to view XML and process it using XSL on the client browser. For now though, the only browser that will do this is Internet Explorer 5 and above. This means that we will need to process the XML on the server and convert its contents to HTML so that visitors can view the guest book.

Once again, we will be using the Microsoft XMLDOM parser to process the XML file, only this time I'll be transforming it by using an XSL stylesheet. 

Thinking logically, we need to step through all of the 'entry' nodes in the XML document and display the contents of each child node in the browser window — we would probably also want to see the entries in descending date order. A simple XSL stylesheet can be created that will perform this task.

The entries will be displayed in an HTML table with a row for each entry. The code required in an XSL stylesheet to perform this could be as simple as this example.
<xsl:for-each select="guestbook/entry" order-by="-entry[@date]"><br>
  <tr><br>
    <td width = "100%"><br>
       <b>Date: </b> <xsl:value-of select="date"/><br/><br>
       <b>Name:</b> <xsl:value-of select="name"/><br/><br>
       <b>Email: </b> <xsl:value-of select="email"/><br/><br>
       <b>HomePage : </b> <xsl:value-of select="homepage"/><br/><br>
       <b>Country : </b> <xsl:value-of select="country"/><br/><br>
       <b>Comment : </b> <pre><xsl:value-of select="comment"/></pre><br/> <br>
       <hr/><br>
    </td><br>
  </tr><br>
</xsl:for-each><br>

The first line (for-each select=...) tells the DOM/XSL parser that we want to step through each entry node underneath the root guestbook node — the order-by instruction instructs the parser to traverse in the descending date order of the date attribute of the entry node. Once inside the for-each loop, we then create a HTML Table row and populate the single column with the child node data elements for each entry in the guest book.

ASP Creation of the HTML Using the XSL Stylesheet

In order to view the guest book from any browser, I'll create an Active Server Page document called 'viewguestbook.asp'. This will instruct the Web server to perform the following tasks:

  1. Create a DOM object for the XML and a DOM object for the XSL file
  2. Load the XML file and the XSL file into their DOM objects
  3. Transform the XML into HTML using the XSL stylesheet DOM object.

The ASP code for these tasks is incredibly simple.

  Dim oSource     ' our XML document
  Dim oStyle      ' our XSL document

'
' Create the XML DOM Object for the XML file
'

  Set oSource = Server.CreateObject("Microsoft.XMLDOM")
  oSource.async = False
'
' Load in the XML file to the DOM object
'
  oSource.Load Server.MapPath("gbook.xml")

'
' Create the XML DOM Object for the XSL Stylesheet
'

  Set oStyle = Server.CreateObject("Microsoft.XMLDOM")
  oStyle.async = False
'
' Load the XSL file into the Style DOM object
'
  oStyle.load Server.MapPath("gbook.xsl")

'
' Write the transformed document out to the browser
'
  Response.Write oSource.TransformNode(oStyle)
'

The last line does all of the transformation work on the server and simply writes the result back to the clients browser. This removes the dependancy of the client using Internet Explorer 5 to view the XML data.

Figure 2 shows what the completed application should look like.

Conclusion

This article, should have given you a fairly good idea as to how easy it can be to use XML as a data store. A simple guest book application is just the tip of the iceberg. The same principles used in this demonstration can be used to build a discussion forum or any other kind of data recording online system (even down to a page statistics tracker). The use of XSL and XML processing on the server is 'big-business' these days, and by using ASP and the Microsoft DOM Parser, you have access to some very powerful functionality. XSL allows you to change the styles of your pages and the way that you view the XML data — this example could quite easily be changed to provide different views of the XML data by simply changing the XSL file.

Almost no one learns from just reading about code so I've included a source code example for download. You can also see this same application running live on our sourceDNA Web site.

source code example

About the author:

Besides running the Visual Basic section of CodeGuru, Chris also maintains the popular VB Code Library Web site. To contact Chris or find out more about his work, visit sourceDNA where Chris writes about the different Web-based technologies used in today's distributed development environments.


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


XML Archives

Whitepaper: Embeddable Content Platform for OEM's
Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Whitepaper: XML Processing in Applications--Take the Next Step

Access FREE IPSWITCH Networking Tools:
Download:
WhatsUp Gold Premium Edition v12
Download:
WhatsUp Gold Distributed Edition v12 - Central Site
Download:
WhatsUp Gold Distributed Edition v12 - Remote Site


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES