Programmatically Apply XSLT in a Dynamic Java Application

s XML has increased in popularity, the number of applications and uses for it has increased exponentially. Developers are rapidly realizing XML’s true power and flexibility of as both a language and a platform-neutral medium for context-aware data.

One of the more popular areas of XML development has been using the eXtensible Stylesheet Language for Transformations (XSLT) to transform XML data. With the simple yet powerful language that XSLT defines, you can sort, format, query, convert, and otherwise manipulate XML to best suit your Java applications.

This 10-Minute Solution introduces XSLT and explores the Java API for XML Processing (JAXP) transformation API. It concludes with a practical, step-by-step example for using XSLT within a J2EE Web application via JAXP’s abstraction layer.



What exactly is XSLT and how can I utilize it in my J2EE applications?



Use JAXP’s transformation API to apply XSLT transforms to XML documents.

What is XSLT?
XSLT provides an elegant, yet powerful mechanism for dynamically modifying the format, content, and organization of XML documents. Because XSLT is, itself, defined using XML, it also is a vendor-, platform-, and language-neutral standard, making it very flexible. Its variety of uses include:

  • Serving data to clients with different formatting requirements (WML, XML, HTML, pure text, etc.)
  • Extracting certain data from a large XML stream or file
  • Displaying information conditionally (based upon weather, time of day, security privileges, etc.)
  • Seamlessly integrating content from multiple sources
  • Maintaining a flexible display that can be easily modified

It also supports many advanced transformation features, such as conditional logic, loops, and a very powerful template-matching mechanism. All the transformation instructions are defined in a single XSL file. When you want to apply a particular XSL stylesheet to an XML file, simply declare this instruction with the following line:

XSLT applies transformation rules to parts of the XML input tree and transforms it into a different XML output tree. The language uses a template-driven mechanism for defining and applying these transformations. Each template consists of a set of transformations that it applies to all or part of an XML node, and the template indicates which node it applies to by specifying that it matches the name of a particular XML element. This element will then serve as the root node for the transformations defined within that template.

Basic XSLT Syntax
Every XSLT stylesheet begins with a header section, which contains the file’s XML declaration, the root element, and a namespace declaration. Thus, your stylesheets should always follow this pattern:

	version=”1.0″>	

One or more XSL templates (indicated by the tag) live between the tags. The data from the XML file will be inserted into these templates. The template element includes an optional match attribute, which enables it to target a specific node to transform within the XML document. At least one template in every stylesheet must include a match attribute specifying either the value “/” or the name of the root element. This indicates which template should serve as the starting point for applying transformations.

To invoke one template from another, the tag causes all matching templates to be processed and their output to be inserted into the output tree at that exact point. This tag supports a select attribute, which allows the tag to specify a particular template rather than apply all templates.

  Some Title           

This is a dynamic page generated by an
XSLT Stylesheet


Here comes someElement


Here comes otherElement

A variety of other templates are called from the main template (the root template indicated by name or with a “/”). In this situation, a template very often will be matched to a particular type of element that appears multiple times. This means that template will be called once for each element of that type. Utilizing the tag to insert dynamic values from the XML input tree into the XML output tree template is often desirable. The tag includes a select attribute through which an XML element name for the current node (determined based upon the template match) can be matched and the value extracted at runtime:

  

JAXP Transformations
JAXP provides an abstract framework for parsing XML documents, and it is independent of a specific parser implementation. Rather than directly instantiating processing and transformation objects, JAXP employs a factory design pattern and provides static methods that return instances of the appropriate type.

Through the factory class, you can specify the properties of the object that will be returned and query an object of that type to see which properties have been set. The abstraction layer outlined by the JAXP specification essentially defines a pluggability layer. This layer allows any JAXP-compliant parser to be “plugged-in” at runtime to fulfill the parsing commands sent from the application component via the JAXP API.

The JAXP transformation API (previously know as the TRaX API) can be used for transforming XML programmatically via SAX or DOM or declaratively by applying an XSLT stylesheet. The transformation API is primarily contained within two packages: javax.xml.transform and javax.xml.transform.stream.

To apply an XSLT stylesheet to an XML document via JAXP, begin by obtaining an instance of a TransformerFactory object from its corresponding factory (yes, you’ll obtain a factory from a factory):

try {    TransformerFactory  tFactory =
TransformerFactory.newInstance();

The next step is to create a Transformer object. Use the XSL source file as an argument to pass into the TransformerFactory‘s static newTransformer() factory method:

Source xslSource = new 
StreamSource( “test.xsl” );Transformer transformer =
tFactory.newTransformer( xslSource );

Now you have a Transformer object that has adopted the XSL templates as a natural part of its transformation process. You can now perform the transformation by invoking the Transformer class’s transform() method.

You must supply two arguments to the transform() method. The first must be of type javax.xml.transform.Source. Any object whose class implements the Source interface can be used as the source for a JAXP transformation. The second argument must be of type javax.xml.transform.Result. Any object whose class implements the Result interface can be used as the result for a JAXP transformation.

The following code will perform a transformation using the Transformer object created earlier (which has been set with the template transformations specified in the test.xsl stylesheet):

    transformer.transform( new 
StreamSource( “test.xml” ), new StreamResult( new
FileOutputStream( “test_output.txt” ) );} catch( Exception ex )
{ ex.printStackTrace(); }

The transformation will be applied using the test.xml file as the XML input tree, and the resulting output will be sent to a file named test_output.txt.

XSLT and J2EE: A Practical Example
Now let’s take a look at a practical J2EE example. You’ll need a JAXP-compliant XML parser (basic XML parsing) and a JAXP-compliant XML processor (for XSLT processing). You also will need a Web server with a J2EE servlet container. If you do not already have these, download the Java Web Services Developers Pack (JWSDP) from Sun Microsystems’ Web site. In addition to other tools and APIs, the JWSDP contains the JAXP API, an XML parser (Xerces), an XML processor (Xalan), and a Web server with a J2EE servlet container (Tomcat 4.0).

If you are using the JWSDP, be sure that you have the following environment variables set:

Variable NameVariable Value
JAVA_HOMEThe root of your JDK directory
JWSDP_HOMEThe root of your JWSDP distribution
PATHBin directories for J2SE and JWSDP should appear first in this list.

For your J2EE application, you will write a simple servlet. Your servlet will accept an HTTP parameter that indicates the XML file to display (via the XSLT stylesheet). It then will locate the file and associated stylesheet, apply the transformation, and push the results back to the client.

Writing the app begins with a series of imports and the basic servlet class declaration:

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import javax.xml.transform.*;import javax.xml.transform.stream.*;public class XSLTServlet extends HttpServlet {

Next, instantiate a TransformerFactory object and create a String to represent the directory where the XML and XSL stylesheets can be located.

  TransformerFactory tFactory = 
TransformerFactory.newInstance(); String directory =
“%JWSDP_HOME%\webapps\jaxpack\WEB-INF\”;

Define the remainder of the servlet in this doGet() method:

  public void doGet( HttpServletRequest req, 
HttpServletResponse res ) throws IOException, ServletException { String page = directory + req.getParameter(“page” ); if( page != null ) { try { Transformer trans =
tFactory.newTransformer( new StreamSource( page + “.xsl” ) ); trans.transform(
new StreamSource( page + “.xml” ), new StreamResult( res.getOutputStream() ) );
} catch( TransformerException te )
{ te.printStackTrace(); } } else { PrintWriter out = res.getWriter(); out.println(“Page parameter missing.” ); }//end if( page != null ) }//end doGet()}//end class XSLTServlet

The value of the page parameter is retrieved from the request and used in conjunction with the directory variable defined earlier to construct the path to the XML files. Once the transformation takes place, the result is funneled into the response object’s output stream.

Now all you do is deploy this servlet within a new or existing Web application and start up Tomcat (via the startup script contained in the bin directory). Modify the directory name that is hard-coded as the value for the directory variable so that it reflects the name and location of this Web application. Place an XML file and the corresponding XSL file into the WEB-INF directory for the application (they should have identical names but different extensions).

Finally, punch “http://localhost:8080/WEB-APP-NAME/servlet/XSLTServlet?page=Weather” into your Web browser to access your application (substitute the word Weather for whatever you named your XML and XSL files). The application searches the designated directory for two files, one named Weather.xml and the other named Weather.xsl. It then applies the transformations defined in the stylesheet to the data in the XML file and pushes the results onto the output stream buffer.

Now that you understand how the XSLT mechanism works, you see how an entire J2EE Web site’s content could be described and transformed for display using XML.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS