Programmatically Apply XSLT in a Dynamic Java Application

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.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1