Transform XML documents with XSLT in Java

Transform XML documents with XSLT in Java

XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents like CSS for HTML documents. XSLT (EXtensible Stylesheet Language Transformation) is a language to transform XML document into another XML document or other formats such as HTML, plain text or into XSL Formatting Objects. With XSLT, you can add elements and attributes to the output file or remove it from the output. You can also sort elements and make decisions about which elements to hide and display. Think of XSLT as a scripting language for transforming XML documents. In this post we will see how to transform XML documents with XSLT in Java language.

How XSLT works

XSLT uses XPath expressions to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents. If you are not aware of XPath, you can refer my other post.

In the transformation process, XSLT uses XPath expressions to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document. Below image shows how XSLT works.

working or xslt

Transform XML into HTML using XSLT in Java

We will transform the below XML file into HTML.


Now we need to create an XSL Style Sheet with a transformation template. Below is the XSL stylesheet which defines how the output HTML should look.


Now the XML and the XSL transformation document is ready.  The XSLT is very simple. It presents the data in tabular format with the help of HTML. Using the for-each construct <xsl:for-each>, we iterate over the employee elements and put each employee details in separate row using <xsl:value-of> tag which puts the value of the selected node as text. Now we need to apply this XSL on the given XML document and generate the HTML document using a Java program.

Java Program to transform XML to HTML

The  javax.xml.transform package provides classes which helps in performing a transformation from source to result.

Below is the output printed to the console on running the above program.

and below is the screenshot of the file created in D drive.

XML to HTML with XSLT in Java

Hope you learned how to transform XML documents with XSLT in Java. If you have any comments, post it in the comments section.

Additional Resources

XSLT Tutorial – w3schools

XSLT Tutorial – tutorialspoint

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
One comment

Add Comment

Required fields are marked *. Your email address will not be published.