O'Reilly logo

XSLT Cookbook by Sal Mangano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Populating a Form

Problem

You want to merge XML data into a predesigned form before delivering it to the client.

Solution

Provided you use XHTML or otherwise create well-formed HTML, you can use XSLT to merge an HTML document with data in an XML document. Here we will merge data in an XML document with a boilerplate HTML form. For example, imagine that your company’s web designer created a form used when online customers are ready to complete a purchase. The form needs to add sales tax, based on the state selected by the customers, when entering their billing addresses. Since the states your company must collect tax for and the tax rates themselves can change, hardcoding these rates into the form would not be a good idea. Instead, you could have the server merge the tax data into the form dynamically by using XSLT.

The sales tax data might be stored (or extracted from a database) like this:

<salesTax>
  <state>
    <name>AL</name>
    <tax>4</tax>
  </state>
  <state>
    <name>AK</name>
    <tax>0</tax>
  </state>
  <state>
    <name>AZ</name>
    <tax>5.6</tax>
  </state>
   
...
   
  <state>
    <name>WY</name>
    <tax>4</tax>
  </state>
</salesTax>

The boilerplate HTML form might look like this:

<html> <head> <title>Check Out</title> <script type="text/javascript" language="JavaScript"> <!-- /* Initialize tax for default state */ setTax(document.customerInfo.billState) /*Recompute tax when state changes */ function setTax(field) { var value = new String(field.value) var commaPos = value.indexOf(",") var taxObj = document.customerInfo.tax ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required