This tutorial explains how to transform Java classes using XSLT templates. XSLT is a language that transforms XML documents to another format, such as HTML, PDF or XML with different structure. JAXB lets you treat your Java objects as if they were XML documents. We can therefore leverage the existing javax.xml.transform APIs to transform Java objects using XSLT.

This tutorial is part of a series of articles on JAXB:

The Domain Model

This tutorial uses a simple JAXB Java domain. A Company has a name and a list of Employees.

This is the Company class:

This is the Employee class:

The XSLT Template

This XSLT template transforms our Java classes into HTML.

Don’t worry if you don’t know much about XSLT. This tutorial only focuses on how to transform using XSLT rather than creating XSLT templates. If you want to know more about XSLT, you can start with this XSLT Tutorial.

Transforming JAXB to HTML

The XsltDemo below has three steps:

  • Creates a Company with two Employees
  • Creates a javax.xml.transform.Transformer instance based on the company.xsl XSLT template
  • Transforms a JAXB Java class into HTML

The Transformer class transforms from an XML Source to an XML Result. JAXBSource implements the Source interface. This enables the XSLT Transformer to use JAXB objects as if they were XML documents.

This is the generated HTML:


The following two tabs change content below.

Eduard Manas

Eduard is a senior IT consultant with over 15 years in the financial sector. He is an experienced developer in Java, C#, Python, Wordpress, Tibco EMS/RV, Oracle, Sybase and MySQL.Outside of work, he likes spending time with family, friends, and watching football.

Latest posts by Eduard Manas (see all)

Leave a Reply