Developer

Pass parameters to XSL templates programmatically

Programmatically passing parameters to XSL templates can appear intimidating at first, but it isn't all that hard. See how to use a HashMap object to store the parameters you want to pass to your template.


Imagine that you have a list of items in an XML document that you need to display to a user on a Web page. Users will need to select which column they want to sort on and the order of the sort. If you're using XSL to convert the XML document to HTML, this might sound complicated. But passing parameters to the XSL template that performs the conversion is easier than you think.

A sample order document
Listing A shows a simple XML document with three items in it. We want to convert the XML document into an HTML one. To do this, we'll use the simple XSL template shown in Listing B.

Translating with Java
To pass parameters to our template programmatically, we’ll need to perform our transformation programmatically. We’ll use the Apache Software Foundation’s Xalan product to process our XSL template. Listing C shows the code that performs this translation and passes parameters to our template.

The main method is called when the class is run from the command line. We’ve hard-coded the names of our order document and our XSL template into this method. Our class includes a simple function for creating new Source objects from files identified by a filename, and we'll use this to pull in our order document and template.

Next, we'll use a HashMap object to store the parameters (column and order) we want to pass to our template. The transform method handles the actual XSL translation by creating a Transformer class from the TransformerFactory. The parameters to the translation are sent using the setParameter method of the Transformer class. We'll use an iterator to step through each entry in our HashMap and set the parameters. Each parameter that is set is available to the XSL template, as shown in Listing D. The <xsl:param /> elements at the top of the template identify the incoming parameters and provide default values if the parameters are missing.

Parameterizing XSL templates may seem complicated at first, but once you try, you’ll find yourself reducing your coding time.

We want your feedback
Tell us what you think about this tip on passing parameters to XSL templates programmatically. Post your comments below or contact the editors.

 

 

 

 

 

Editor's Picks