Pradeep's Blog

Google

Monday, July 03, 2006

Passing parameters to XSL from Java

Generating a HTML from XML can be done using the javax.xml.transform class in the Java’s API. The transformation can be done using the code below;

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer
(new javax.xml.transform.stream.StreamSource(xslFileName));
transformer.transform(new javax.xml.transform.stream.StreamSource
(xmlFileName),new javax.xml.transform.stream.StreamResult
( new FileOutputStream(htmlFileName)));

Note: Remember to provide the correct XSL, XML and HTML file names and the XSL and the XML file should be valid (i.e. all tags should be closed properly)

Now, suppose you want to customise the HTML output depending on certain criteria in your program, how do you do that? This can be done by sending information to the XSL file as parameters. So, the next big question, how can parameters be passed into the XSL file from a java programme?
The javax.xml.transform class provides you with a method called setParameter(String name, Object value). An example of this is given below;

Timestamp ts = new Timestamp(System.currentTimeMillis());
transformer.setParameter("timestamp", ts);

Here the timestamp is passed to the XSL filename. The XSL file can get this value by using a global param field as shown below.
<xsl:param name="timestamp"/>

and used like this
<xsl:value-of select="$timestamp"/>

to print the time that is obtained from the java class.

Note: The parameter name in the XSL should match the one in the java class.

0 Comments:

Post a Comment

<< Home