XSL - Java working with XML overview (tutorial)

Complete Source Code for all examples below

XSL is very powerfull mechnism of templating data. It can be used in many areas, such as HTML page generation, email generation and many other where you need to put your XML data in some sort of template to make it nice.

In order to do the transformation you need two things: the XML document and the XSL template. There are lots of things to know about the XSL and I suggest you to read the w3c specifications. In this overview we will do a simple example.


Simple Example:

You have stock list in the form of XML and you need to generate an HTML page that looks like a table with SKU's (Stock Keeping Unit) and some of their attribution


The XML (source):


    Smoking pipe

The XSL (template):




The code to work this:


package dp.test.xml.xls;

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.junit.Test;

public class XSLTransformExample

	public void testSimpleTransformationExample() throws TransformerException {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer(
				new StreamSource(XSLTransformExample.class.getResourceAsStream("stock.xsl")));
		final StringWriter writer = new StringWriter();
				new StreamSource(XSLTransformExample.class.getResourceAsStream("stock.xml")), 
				new StreamResult(writer));

The output:


PIPESmoking pipe10.9010


  • Transformer can be obtaine through the TransformerFactory by supplying a valis XSL
  • Invoking transform method on the XML will result in streaming the result
This page was last updated on: 13/04/2012 11:10