Transforming XML to HTML using XSLT


Here we will see the example on transforming XML to HTML using XSLT. We can also use Java code to transform XML to HTML but that would require a many LoC to finish the job but using XSLT it is quite easy to transform. XSLT stands for XSL Transformations.

The Extensible Stylesheet Language (XSL) is a family of recommendations and styling language for defining XML document transformation and presentation. It consists of three parts:

  • XSL Transformations (XSLT) : a language for transforming XML;
  • The XML Path Language (XPath) : an expression language used by XSLT (and many other languages) to access or refer to parts of an XML document;
  • XSL Formatting Objects (XSL-FO) : an XML vocabulary for specifying formatting semantics.

Related Posts:

Wiki says the original document is not changed; rather, a new document is created based on the content of an existing one. Typically, input documents are XML files, but anything from which the processor can build an XQuery and XPath Data Model can be used, such as relational database tables or geographical information systems.

Although XSLT is designed as a special-purpose language for XML transformation, the language is Turing-complete, making it theoretically capable of arbitrary computations.

Let’s see how to use XSLT to transform XML documents into into HTML.


Eclipse 2020-06, At least Java 1.8, Knowledge of HTML & XML

Project Setup

Create gradle or maven based project in Eclipse. The name of the project is java-xslt-xml-to-html.

If you are creating gradle based project in Eclipse then you can use the below build.gradle script:

plugins {
    id 'java-library'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {

If you are creating maven based project then you can use below pom.xml file:

<project xmlns="" xmlns:xsi=""
		<java.version>at least 1.8</java.version>

XML File

Now put the below XML file books.xml under src/main/resources/xml directory.

In the below XML file you can see we have lots of data which can be easily displayed on HTML file in a table format.

Here we have root node catalog and under this we have several book nodes. We have the book id as an attribute on the book node. We will also see how to extract this id attribute using XSLT.

<?xml version="1.0"?>
	<book id="bk101">
		<author>Gambardella, Matthew</author>
		<title>XML Developer's Guide</title>
		<description>An in-depth look at creating applications
			with XML.
	<book id="bk102">
		<author>Ralls, Kim</author>
		<title>Midnight Rain</title>
		<description>A former architect battles corporate zombies,
			an evil sorceress, and her own childhood to become queen
			of the world.
	<book id="bk103">
		<author>Corets, Eva</author>
		<title>Maeve Ascendant</title>
		<description>After the collapse of a nanotechnology
			society in England, the young survivors lay the
			foundation for a new society.
	<book id="bk104">
		<author>Corets, Eva</author>
		<title>Oberon's Legacy</title>
		<description>In post-apocalypse England, the mysterious
			agent known only as Oberon helps to create a new life
			for the inhabitants of London. Sequel to Maeve
	<book id="bk105">
		<author>Corets, Eva</author>
		<title>The Sundered Grail</title>
		<description>The two daughters of Maeve, half-sisters,
			battle one another for control of England. Sequel to
			Oberon's Legacy.
	<book id="bk106">
		<author>Randall, Cynthia</author>
		<title>Lover Birds</title>
		<description>When Carla meets Paul at an ornithology
			conference, tempers fly as feathers get ruffled.
	<book id="bk107">
		<author>Thurman, Paula</author>
		<title>Splish Splash</title>
		<description>A deep sea diver finds true love twenty
			thousand leagues beneath the sea.
	<book id="bk108">
		<author>Knorr, Stefan</author>
		<title>Creepy Crawlies</title>
		<description>An anthology of horror stories about roaches,
			centipedes, scorpions and other insects.
	<book id="bk109">
		<author>Kress, Peter</author>
		<title>Paradox Lost</title>
		<genre>Science Fiction</genre>
		<description>After an inadvertant trip through a Heisenberg
			Uncertainty Device, James Salway discovers the problems
			of being quantum.
	<book id="bk110">
		<author>O'Brien, Tim</author>
		<title>Microsoft .NET: The Programming Bible</title>
		<description>Microsoft's .NET initiative is explored in
			detail in this deep programmer's reference.
	<book id="bk111">
		<author>O'Brien, Tim</author>
		<title>MSXML3: A Comprehensive Guide</title>
		<description>The Microsoft MSXML3 parser is covered in
			detail, with attention to XML DOM interfaces, XSLT processing,
			SAX and more.
	<book id="bk112">
		<author>Galos, Mike</author>
		<title>Visual Studio 7: A Comprehensive Guide</title>
		<description>Microsoft Visual Studio 7 is explored in depth,
			looking at how Visual Basic, Visual C++, C#, and ASP+ are
			integrated into a comprehensive development


Next create the XSLT file called Xslt2Html.xsl and put it under src/main/resources/xslt directory.

Here the standard format of XSLT is to keep everything inside the tag <xsl:stylesheet/>. You also need to specify the namespace xmlns:xsl="" for the XSLT. Then we have <xsl:template/> tag that matches root node catalog and starts processing from this root node.

Next we want to select the XML data and display into HTML format. That’s why we have used HTML tags here. We have also used some css to style the alternate rows data. Then we are iterating each node (book) and selecting the values.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
	<xsl:template match="/catalog">
					table {
					font-family: arial, sans-serif;
					border-collapse: collapse;
					td, th {
					border: 1px solid #dddddd;
					text-align: left;
					padding: 8px;
					tr:nth-child(even) {
					background-color: #dddddd;
						<th>Publish Date</th>
					<xsl:for-each select="book">
								<xsl:value-of select="book/@id" />
								<xsl:value-of select="author" />
								<xsl:value-of select="title" />
								<xsl:value-of select="genre" />
								<xsl:value-of select="price" />
								<xsl:value-of select="publish_date" />
								<xsl:value-of select="description" />

Transform XML to HTML

Write the Java class to transform the XML file data to HTML using XSLT file. We have put both XML and XSLT files under classpath and finaly transforms the XML data into HTML output. We write the output to the HTML file called books.html under the project’s root directory.



import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XmlToHtmlTransformer {

	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException,
			TransformerFactoryConfigurationError, TransformerException {
		transform("xml/books.xml", "xslt/Xslt2Html.xsl");

	public static void transform(final String xml, final String xslt) throws SAXException, IOException,
			ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {

		ClassLoader classloader = XmlToHtmlTransformer.class.getClassLoader();
		InputStream xmlData = classloader.getResourceAsStream(xml);
		URL xsltURL = classloader.getResource(xslt);

		Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlData);
		Source stylesource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm());
		Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

		StringWriter stringWriter = new StringWriter();
		transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter));

		// write to file
		File file = new File("books.html");
		if (!file.exists()) {

		FileWriter fw = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fw);


Testing the Application

Run the above main class, you will find books.html file under the project’s root directory.

Now open the books.html file in Web Browser in Eclipse. You will see the final XML data in tabular format on the Eclipse Web Browser. You can also open the output HTML file in browser.

xml to html using xslt

Source Code


Thanks for reading.

Related posts

Leave a Comment