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.

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.

Prerequisites

Knowledge of HTML and XML

Please go through the following instructions in order to create project in Eclipse and transform XML to HTML using XSLT

Step 1. Create Gradle based eclipse project called xslt-xml. The build.gradle file should look similar to below

apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8

Step 2. Once the project gets created it should look similar to below image

xml to html using xslt

Step 3. 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"?>
<catalog>
	<book id="bk101">
		<author>Gambardella, Matthew</author>
		<title>XML Developer's Guide</title>
		<genre>Computer</genre>
		<price>44.95</price>
		<publish_date>2000-10-01</publish_date>
		<description>An in-depth look at creating applications
			with XML.
		</description>
	</book>
	<book id="bk102">
		<author>Ralls, Kim</author>
		<title>Midnight Rain</title>
		<genre>Fantasy</genre>
		<price>5.95</price>
		<publish_date>2000-12-16</publish_date>
		<description>A former architect battles corporate zombies,
			an evil sorceress, and her own childhood to become queen
			of the world.
		</description>
	</book>
	<book id="bk103">
		<author>Corets, Eva</author>
		<title>Maeve Ascendant</title>
		<genre>Fantasy</genre>
		<price>5.95</price>
		<publish_date>2000-11-17</publish_date>
		<description>After the collapse of a nanotechnology
			society in England, the young survivors lay the
			foundation for a new society.
		</description>
	</book>
	<book id="bk104">
		<author>Corets, Eva</author>
		<title>Oberon's Legacy</title>
		<genre>Fantasy</genre>
		<price>5.95</price>
		<publish_date>2001-03-10</publish_date>
		<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
			Ascendant.
		</description>
	</book>
	<book id="bk105">
		<author>Corets, Eva</author>
		<title>The Sundered Grail</title>
		<genre>Fantasy</genre>
		<price>5.95</price>
		<publish_date>2001-09-10</publish_date>
		<description>The two daughters of Maeve, half-sisters,
			battle one another for control of England. Sequel to
			Oberon's Legacy.
		</description>
	</book>
	<book id="bk106">
		<author>Randall, Cynthia</author>
		<title>Lover Birds</title>
		<genre>Romance</genre>
		<price>4.95</price>
		<publish_date>2000-09-02</publish_date>
		<description>When Carla meets Paul at an ornithology
			conference, tempers fly as feathers get ruffled.
		</description>
	</book>
	<book id="bk107">
		<author>Thurman, Paula</author>
		<title>Splish Splash</title>
		<genre>Romance</genre>
		<price>4.95</price>
		<publish_date>2000-11-02</publish_date>
		<description>A deep sea diver finds true love twenty
			thousand leagues beneath the sea.
		</description>
	</book>
	<book id="bk108">
		<author>Knorr, Stefan</author>
		<title>Creepy Crawlies</title>
		<genre>Horror</genre>
		<price>4.95</price>
		<publish_date>2000-12-06</publish_date>
		<description>An anthology of horror stories about roaches,
			centipedes, scorpions and other insects.
		</description>
	</book>
	<book id="bk109">
		<author>Kress, Peter</author>
		<title>Paradox Lost</title>
		<genre>Science Fiction</genre>
		<price>6.95</price>
		<publish_date>2000-11-02</publish_date>
		<description>After an inadvertant trip through a Heisenberg
			Uncertainty Device, James Salway discovers the problems
			of being quantum.
		</description>
	</book>
	<book id="bk110">
		<author>O'Brien, Tim</author>
		<title>Microsoft .NET: The Programming Bible</title>
		<genre>Computer</genre>
		<price>36.95</price>
		<publish_date>2000-12-09</publish_date>
		<description>Microsoft's .NET initiative is explored in
			detail in this deep programmer's reference.
		</description>
	</book>
	<book id="bk111">
		<author>O'Brien, Tim</author>
		<title>MSXML3: A Comprehensive Guide</title>
		<genre>Computer</genre>
		<price>36.95</price>
		<publish_date>2000-12-01</publish_date>
		<description>The Microsoft MSXML3 parser is covered in
			detail, with attention to XML DOM interfaces, XSLT processing,
			SAX and more.
		</description>
	</book>
	<book id="bk112">
		<author>Galos, Mike</author>
		<title>Visual Studio 7: A Comprehensive Guide</title>
		<genre>Computer</genre>
		<price>49.95</price>
		<publish_date>2001-04-16</publish_date>
		<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
			environment.
		</description>
	</book>
</catalog>

Step 4. 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=”http://www.w3.org/1999/XSL/Transform” 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"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:template match="/catalog">
		<html>
			<head>
				<style>
					table {
						font-family: arial, sans-serif;
						border-collapse: collapse;
						width:
						100%;
					}
					td, th {
						border: 1px solid #dddddd;
						text-align: left;
						padding: 8px;
					}
					tr:nth-child(even) {
						background-color: #dddddd;
					}
				</style>
			</head>
			<body>
				<h2>Books</h2>
				<table>
					<tr>
						<th>Id</th>
						<th>Author</th>
						<th>Title</th>
						<th>Genre</th>
						<th>Price</th>
						<th>Publish Date</th>
						<th>Description</th>
					</tr>
					<xsl:for-each select="book">
						<tr>
							<td>
								<xsl:value-of select="book/@id" />
							</td>
							<td>
								<xsl:value-of select="author" />
							</td>
							<td>
								<xsl:value-of select="title" />
							</td>
							<td>
								<xsl:value-of select="genre" />
							</td>
							<td>
								<xsl:value-of select="price" />
							</td>
							<td>
								<xsl:value-of select="publish_date" />
							</td>
							<td>
								<xsl:value-of select="description" />
							</td>
						</tr>
					</xsl:for-each>
				</table>
			</body>
		</html>
	</xsl:template>
</xsl:stylesheet>

Step 5. 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 arite the output to the HTML file called books.html under the project’s root directory.

package com.jeejava.transform;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
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 javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XmlToHtmlTransformer {
	public void transform() throws SAXException, IOException, ParserConfigurationException,
						TransformerFactoryConfigurationError, TransformerException {
		InputStream xmlData = getClass().getClassLoader().getResourceAsStream("xml/books.xml");
		URL xsltURL = getClass().getClassLoader().getResource("xslt/Xslt2Html.xsl");
		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()) {
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(stringWriter.toString());
		bw.close();
	}
}

Step 6. In order to test the application create below main class

package com.jeejava.main;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.xml.sax.SAXException;
import com.jeejava.transform.XmlToHtmlTransformer;
public class Application {
	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException,
						TransformerFactoryConfigurationError, TransformerException {
		XmlToHtmlTransformer xmlToHtmlTransformer = new XmlToHtmlTransformer();
		xmlToHtmlTransformer.transform();
	}
}

Step 7. Run the 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.

xml to html using xslt

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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