Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: XSLT blooms with Java

XSLT blooms with Java

Tutorial Details:

XSLT blooms with Java
XSLT blooms with Java
By: By Taylor Cowan
Use Java in your stylesheets when XSLT won't do the trick
ave you ever been stumped by a difficult XML transformation issue that you couldn't solve with XSLT (Extensible Stylesheet Language Transformation) alone? Take, for example, a simple filter stylesheet that selects only those nodes dated earlier than five days ago. You've heard that XSLT can filter XML documents, so you figure you'll solve this problem in no time. The first task is getting today's date from within a stylesheet, provided that information is not included in the original XML document. Unfortunately, you cannot complete this task with only XSLT. In a situation such as this, you can simplify your XSLT code and solve the problem faster with a Java extension.
Many XSLT processors allow for some type of extension mechanism; the specification requires them to do so. In the world of Java and XML, the most widely used XSLT processor is the open source Apache Xalan processor. Written in Java, Xalan allows for extensions in Java. Many developers find Xalan's extensibility powerful because it lets them utilize their Java skills from within the stylesheet context. Consider the way JSPs (JavaServer Pages), scriptlets, and custom tags add power to HTML. Xalan extensions add power to stylesheets in much the same way: by allowing Java developers access to their favorite tool, Java.
In this article, I will demonstrate how you can use Java from within an XSLT stylesheet. First, we will use Xalan's extensibility to instantiate and use existing classes within the JDK. Later, I'll show you how to write an XSLT extension function that takes a String argument and returns a DOM (Document Object Model) fragment to the stylesheet processor.
XSLT is important for J2EE (Java 2 Platform, Enterprise Edition) developers because styling XML documents has become a server-side operation. Also, JAXP (the Java API for XML Processing), which includes support for XSLT engines, has become part of the J2EE specification ( J2EE 2.6.11 ). In its infancy, XSLT was intended to style XML on the client; however, most applications style the XML before sending it to the client. For J2EE developers, this means that the XSLT processor will most likely run within the app server.
Before you continue with this article, be warned that using Java extensions in your XSLT stylesheets will reduce their portability. While extensions are part of the XSLT specification, the way they are implemented is not. If your stylesheets will run on processors other than Xalan, such as Internet Explorer's stylesheet engine, you should avoid using extensions at all costs.
XSLT weaknesses
Because XSLT has some weak spots, XSLT extensions prove quite useful. I'm not saying that XSLT is bad; however, it just doesn't offer the best tool for processing everything in an XML document. Consider this section of XML:

XSLT isn't as easy to use as some would have you
...


Suppose your boss asks you to modify a stylesheet so that it converts all instances of "isn't" to "is not" and localizes common labels. Certainly XSLT provides a mechanism to do something along these lines, right? Wrong. XSLT provides no easy way to replace the occurrence of a word or pattern within a string. The same goes for localization. That's not to say it can't be done with standard XSLT syntax. There are ways, but they are not nearly as easy as we would like. If you really want to write text manipulation functions using recursive templates, be my guest.
XSLT's main weakness is text processing, which seems reasonable since its purpose is to render XML. However, because XML content is entirely text, XSLT needs stronger text handling. Needless to say, stylesheet designers require some extensibility from time to time. With Xalan, Java provides this extensibility.
Use JDK classes within XSLT
You might be pleased to know that you don't have to write any Java code to take advantage of Xalan's extensibility. When you use Xalan, you can create and invoke methods on almost any Java object. Before using a Java class, you must provide an XSLT namespace for it. This example declares "java" as a namespace for everything in or under the Java package (i.e., the entire JDK):
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:java="java" >
Now we need something to do. Let's start with a small XML document:

Java May Be a Fad
J. Burke
11/30/97

You've been asked to style this XML so the title appears in uppercase. A developer new to XSLT would simply pop open an XSLT reference to look for the toUpper() function; however, she'd be disappointed to find that the reference lacks one. The translate() method is your best bet, but I have an even better method: java.lang.String.toUpperCase() . To use this method, you need to instantiate a String object with the title contents. Here is how you can create a new String instance with the title element's contents:


The name attribute specifies the handle to your new String instance. You invoke the constructor by first specifying the namespace along with the remaining path to the String class. As you might have noticed, String lacks a new() method. You use new() to construct a Java object in Xalan; it corresponds to Java's new keyword. The arguments given to new() determine the constructor version that will be called. Now that you have the title contents within a Java String object, you can use the toUpperCase() method, like so:

This might look strange to you at first. When using Java methods on a particular instance, the first argument is the instance you want the method invoked on. Obviously Xalan uses introspection to provide this capability.
Below you'll find another trick. Here is how you might emit the date and time anywhere within your stylesheet using java.lang.Date :

Here's something that will make the day of anyone required to localize a generic stylesheet between two or more languages. You can use java.util.ResourceBundle to localize literal text within a stylesheet. Since your XML has an author tag, you might want to print "Author:" next to the person's name.
One option is to create a separate stylesheet for each locale, i.e., one for English, another for Chinese, and so on. The problems inherent in this approach should be evident. Keeping multiple stylesheet versions consistent is time consuming. You also need to modify your application so that it chooses the correct stylesheet based on the user's locale.
Instead of duplicating the stylesheet for each language, you can take advantage of Java's localization features. Localizing with the help of a ResourceBundle proves a better approach. Within XSLT, load the ResourceBundle at the beginning of your stylesheets, like so:
select="java:util.ResourceBundle.getBundle('General')"/>
The ResourceBundle class expects to find a file called General.properties in your CLASSPATH . Once the bundle is created, it can be reused throughout the stylesheet. This example retrieves the author resource:

Notice again the strange method signature. Normally, ResourceBundle.getString() takes only one argument; however, within XSLT you need to also specify the object by which you want to invoke the method.
Write your own extensions
For some rare situations, you might need to write your own XSLT extension, in the form of either an extension function or an extension element. I will discuss creating an extension function, a concept fairly easy to grasp. Any Xalan extension function can take strings as input and return strings to the XSLT processor. Your extensions can also take NodeList s or Node s as arguments and return these types to the XSLT processor. Using Node s or NodeList s means you can add to the original XML document with an extension function, which is what we will do.
One type of text item encountered frequently is a date; it provides a great opportunity for a new XSLT extension. Our task is to style an article element so the date prints in the following format:
Friday, November 30, 2001
Can standard XSLT complete the date above? XSLT can finish most of the task. Determining the actual day is the difficult part. One way to quickly solve that problem is to use the java.text.SimpleDate format class within an extension function to return a string formatted as we wish. But wait: notice that the day appears in bold text. This returns us to the initial problem. The reason we are even considering an extension function is because the original XML document failed to structure the date as a group of nodes. If our extension function returns a string, we will still find it difficult to style the day field differently than the rest of the date string. Here's a more useful format, at least from the perspective of an XSLT designer:

11
30
2001

We now create an XSLT extension function, taking a string as an argument and returning an XML node in this format:

November
30
Friday
2001

The class hosting our extension function doesn't implement or extend anything; we will call the class DateFormatter :
public class DateFormatter {
public static Node format (String date) {}
Wow, too easy, huh? There are absolutely no requirements placed on the type or interface of a Xalan extension function. Generally, most extension functions will take a String as an argument and return another String . Other common patterns are


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
XSLT blooms with Java

View Tutorial:
XSLT blooms with Java

Related Tutorials:

XSL gives your XML some style - JavaWorld June 2000
XSL gives your XML some style - JavaWorld June 2000
 
XML document processing in Java using XPath and XSLT - JavaWorld September 2000
XML document processing in Java using XPath and XSLT - JavaWorld September 2000
 
An open alternative to JSP - The faults of JSP So what's wrong with JSP?
How the template-based, open source API FreeMarker trumps JSP
 
Add XML to your J2EE applications - JavaWorld February 2001
Integrate an XML presentation layer in the J2EE layered architecture
 
XML APIs for databases - JavaWorld January 2000
XML APIs for databases - JavaWorld January 2000
 
XSLT blooms with Java
XSLT blooms with Java
 
Generate JavaBean classes dynamically with XSLT
Generate JavaBean classes dynamically with XSLT
 
Boost Struts with
Boost Struts with XSLT and XML
 
Transform data into Web applications with Cocoon
Transform data into Web applications with Cocoon
 
XML glossary
XML glossary
 
Sun boosts
Sun boosts enterprise Java
 
Transparently cache XSL transformations with JAXP
Transparently cache XSL transformations with JAXP
 
AurigaDoclet: Javadoc doclet for generating javadoc in pdf, postscript, etc
What Is AurigaDoclet? AurigaDoclet is a Javadoc doclet which can generate Java API document in fo, pdf, postscript, pcl, and svg format. AurigaDoclet accepts command line options which can be used to further customize the generated output.
 
NetBeans - XSLT Editor
NetBeans - XSLT Editor
 
FastParser 1.6.3
FastParser 1.6.9.1 XML Edition FastParser is a Java Xml parser High performance XML parser (benchmarks* : up to +100% faster compared to Xerces and JDK1.4 integrated parser) SAX Level 1 and 2 compliant DOM support JAXP compatibility Names
 
Template-Based Code Generation with Apache Velocity, Part 1
Template-Based Code Generation with Apache Velocity, Part I'm going to discuss template-based code generation, explain basic concepts related to templates and transformations, and demonstrate the huge benefits they can bring in code generation.
 
Eclipse - XML / XSLT Plugin
Eclipse - XML / XSLT Plugin A plugin for the eclipse IDE adding XML / XSLT editing facilities
 
Extensible Code Generation with Java, Part 1
Extensible Code Generation with Java, Part 1 Code generation is a key new trend in engineering, one that you need to understand well. The reason is simple: today's modern frameworks are extremely code-intensive. Using a code generator to build the code
 
Getting Groovy with XML
XML sucks. Oh, wait, XML rocks. Well, it actually does a lot of both. It rocks because of all of the editors, validators, and tools written for it. XML has all but replaced any notion of a new custom text-based data language. But it also sucks because it\
 
FOP is the world's first print formatter driven by XSL formatting objects.
It is a Java application that reads a formatting object tree and then turns it into a PDF document. The formatting object tree, can be in the form of an XML document (output by an XSLT engine like XT or Xalan) or can be passed in memory as a DOM Document
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.