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 ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.