Core Java

Exploring XSLT Processing in Java

Extensible Stylesheet Language Transformations (XSLT), a powerful tool for transforming XML documents into various formats, is a crucial aspect of handling and manipulating XML data in the Java programming environment. This article explores the basics of using (XSLT) in Java.

1. Understanding XSLT

XSLT is a language used for transforming XML documents into different structures or formats. It operates by defining a set of rules, called templates, that specify how the input XML should be transformed into the desired output. These templates are written in XSLT, a language specifically designed for this purpose. The XSLT processing model involves applying a stylesheet to an XML document, resulting in a transformed version of that document.

An XSLT stylesheet is a set of instructions written in XSLT language that defines how to transform the content of an XML document. it’s like a guide that tells a computer program how to change the look or structure of an XML document. For example, a stylesheet might instruct the program to take certain elements and display them in a different order, format the text in a particular way, or even exclude certain parts altogether.

2. Key Components of XSLT Processing in Java

2.1 TransformerFactory

The TransformerFactory class in Java provides an instance of the Transformer class, which is responsible for applying XSLT stylesheets to XML documents. It’s a crucial part that helps begin XSLT transformations.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(new StreamSource("stylesheet.xsl"));

2.2 Templates

XSLT stylesheets are represented in Java by the Templates interface. The TransformerFactory processes the stylesheet and produces a Templates object, which is used to create Transformer instances.

Templates templates = transformerFactory.newTemplates(new StreamSource("stylesheet.xsl"));

2.3 Transformation

The actual transformation process involves applying the Transformer to an XML source, producing the transformed result. This can be done with various sources, including files, input streams, or even in-memory representations.

transformer.transform(new StreamSource("input.xml"), new StreamResult("output.html"));

3. Practical Example: HTML Generation from XML

3.1 Understanding the Scenario

Let’s consider a practical example where XSLT is employed to generate HTML from an XML source. Assume we have an XML document representing a list of books in a library. Each book has details like title and author as shown below:


<?xml version="1.0" encoding="UTF-8"?>

<library>
    
    <book>
        <title>Core HTML5 Canvas</title>
        <author>David Geary</author>
    </book>
  
    <book>
        <title>JavaScript and JQuery</title>
        <author>David Sawyer McFarland</author>
    </book>
  
    <book>
        <title>Core Java Fundamentals</title>
        <author>Cay S Horstmann and Gary Cornell</author>
    </book>
    
</library>

The above code is an example of XML (eXtensible Markup Language) that represents a simple library with three books. Let’s break down the code:

  • <library>: This is the root element and represents the entire library. Inside it, there are three <book> elements.
  • <book>: Each <book> element represents an individual book in the library. Inside each <book> element, there are two child elements:
    • <title>: This element contains the title of the book.
    • <author>: This element contains the name of the author of the book.

Now, let’s say we want to display this information on a webpage in a structured HTML format.

3.2 Create the XSLT Stylesheet

To achieve this transformation, we will create an XSLT stylesheet. This stylesheet will define the rules for transforming the elements and attributes from the XML source into HTML elements.

Here is a simple example of creating an XSLT stylesheet named library.xsl located on the path src/main/resources folder in the project:


<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    
  <xsl:template match="/">
    <html>
      <head>
        <title>Library Catalog</title>
      </head>
      <body>
        <h1>Books in the Library</h1>
        <ul>
          <xsl:for-each select="library/book">
            <li>
              <strong>Title:</strong> <xsl:value-of select="title"/><br/>
              <strong>Author:</strong> <xsl:value-of select="author"/>
            </li>
          </xsl:for-each>
        </ul>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

In this XSLT stylesheet, we define a template that matches the root element (“/”). It transforms the XML structure into HTML, creating a list of books with titles and authors. Here’s a breakdown of the above XSLT code:

  • <xsl:stylesheet>: This is the root element of the XSLT stylesheet. It defines the version of XSLT being used (1.0) and declares the XSL namespace.
  • <xsl:output method="html"/>: This specifies that the output of the XSLT transformation should be in HTML format.
  • <xsl:template match="/">: This is the main template that matches the root element of the input XML document. It serves as the entry point for the transformation. Inside this template we have:
    • <html>, <head>, <title>, <body>: These elements define the structure of the HTML document that will be generated.
    • <ul>: This is an unordered list element that will contain the details of each book.
    • <xsl:for-each select="library/book">: This XSLT instruction iterates over each <book> element within the <library> element in the input XML document.
    • Inside this loop, <li>: This generates an HTML list item for each book.
    • <xsl:value-of select="title"/>: This extracts and outputs the title of each book.
    • <xsl:value-of select="author"/>: This extracts and outputs the author of each book.

3.3 Apply the Transformation in Java

Now, let’s use Java to apply this XSLT stylesheet to our XML document:

public class XMLTransformationExample {

    public static void main(String[] args) {
        try {
            
            // Load the XML input file using the ClassLoader
            InputStream xmlInputFile = XMLTransformationExample.class.getClassLoader().getResourceAsStream("library.xml");

            // Load XSLT stylesheet
            InputStream xsltStylesheet = XMLTransformationExample.class.getClassLoader().getResourceAsStream("library.xsl");

            // Create a TransformerFactory
            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            // Create a Transformer based on the XSLT stylesheet
            Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsltStylesheet));

            // Perform the transformation and generate the output System.out
            transformer.transform(new StreamSource(xmlInputFile), new StreamResult(System.out));

            System.out.println("Transformation completed successfully.");

        } catch (TransformerException e) {
            System.err.println("Transformation error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

In the above code:

  • We start by loading the XML input file (library.xml) is using the ClassLoader. library.xml is present in the resources folder of the project.
  • We also load the XSLT stylesheet (library.xsl) using the ClassLoader. Similar to the XML file, library.xsl is present in the resources folder.
  • TransformerFactory transformerFactory = TransformerFactory.newInstance(): This line creates a TransformerFactory instance.
  • Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsltStylesheet)): This line creates a Transformer based on the XSLT stylesheet loaded earlier. It initializes the transformer with the rules defined in the XSLT.
  • Finally, the transformer.transform(...) method is called on the transformer instance. This method takes the input source (library.xml) from StreamSource and transforms it using the XSLT rules and outputs the result to System.out (console).

To transform the output into a *.html file, we apply the transformer.transform() method like this:

transformer.transform(new StreamSource(xmlInputFile), new StreamResult(output.html));

The transformed output is then directed to the specified output destination, which, in this case, is the file output.html which would look like the image below.

Figure 1: Output from extensible stylesheet language transformations example in Java
Figure 1: Output from extensible stylesheet language transformations example in Java

4. Conclusion

In this article, we ventured into the world of XSLT processing with Java, exploring its abilities to transform XML documents into an HTML format.

In conclusion, understanding how Java handles XSLT processing gives us the power to make the most out of transforming XML in our programs. Java’s strong support for XSLT, built into its standard library, makes it easy and effective for dealing with various XML tasks.

5. Download the Source Code

This was an article on Exploring Extensible Stylesheet Language Transformations(XSLT) Processing in Java.

Download
You can download the full source code of this example here: java extensible stylesheet language transformations example

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button