XSL Transformations in Java: Stylesheets and the Transformer API
Turn XML into HTML, text or other XML with XSLT 1.0 from Java: templates and match patterns, apply-templates, value-of, for-each, sort, if and choose, variables and parameters, Templates and Transformer, Source and Result types, a flat file as SAX events, and secure settings.
kvi5hnuCode Sprout team member9 min readOn this page
You've seen how to read XML into Java data and how to write XML out. Often, though, a program needs the same XML in a different shape: an HTML page for people, a CSV or properties file for an older tool, or another XML vocabulary for a partner's system. Writing Java code for each conversion is tedious. XSLT (XSL Transformations) is a declarative language just for this job. A stylesheet describes how each kind of input node should appear in the output, and an XSLT processor applies it.
The JDK includes an XSLT 1.0 processor (derived from Apache Xalan) behind the javax.xml.transform API. XSLT 2.0 and 3.0, with regular expressions, grouping and much more, require a third-party processor such as Saxon. The Java API stays the same.
A stylesheet
Suppose the input lists employees:
<staff>
<employee>
<name>Ada Lovelace</name>
<salary>75000</salary>
<hiredate year="2019" month="12" day="15"/>
</employee>
...
</staff>
and we want an HTML table with one row per employee. A stylesheet is an XML document in the XSLT namespace:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/staff">
<table border="1"><xsl:apply-templates/></table>
</xsl:template>
<xsl:template match="/staff/employee">
<tr><xsl:apply-templates/></tr>
</xsl:template>
<xsl:template match="/staff/employee/name">
<td><xsl:apply-templates/></td>
</xsl:template>
<xsl:template match="/staff/employee/hiredate">
<td><xsl:value-of select="@year"/>-<xsl:value-of select="@month"/>-<xsl:value-of select="@day"/></td>
</xsl:template>
</xsl:stylesheet>
xsl:output chooses the output method: xml (the default), html or text. Each xsl:template has a match pattern, written in XPath (article 43). The template's body is copied to the output, with the xsl: instructions executed.
How processing works
The processor starts at the root node and looks for the template that best matches it. Inside a template, <xsl:apply-templates/> processes the children of the current node, again finding the best template for each. The result is a recursive walk over the input, in which each node is handled by "its" template. When several templates match, the more specific pattern wins, and priority attributes can settle ties.
When no template matches, the built-in rules apply. For elements and the root, they produce nothing themselves but keep processing the children. For text and attributes, they copy the text to the output. That's why <td><xsl:apply-templates/></td> around name outputs the name: the text child is handled by the built-in rule. It's also why stray whitespace and unhandled elements leak into the output. A common fix is an empty template that swallows them, such as <xsl:template match="text()"/>, or <xsl:template match="text()[normalize-space() = '']"/> for whitespace only.
Producing values
<xsl:value-of select="expr"/> writes the string value of an XPath expression evaluated relative to the current node. For an attribute that's its value, for an element it's the concatenation of all text inside it, and for a node set it's the string value of the first node (in XSLT 1.0). Text in the output is escaped automatically, so Grace & Co comes out as Grace & Co in XML and HTML output, and unescaped with the text method.
In attribute values of literal output elements, attribute value templates in braces insert expressions: <person since="{hiredate/@year}">. To compute an attribute with logic, use <xsl:attribute name="..."> inside the element.
More instructions
| Instruction | Purpose |
|---|---|
<xsl:for-each select="..."> | loop over a node set in place, instead of a separate template |
<xsl:sort select="..." data-type="number" order="descending"/> | inside for-each or apply-templates: sort the nodes |
<xsl:if test="..."> | conditional output (there's no else) |
<xsl:choose>, <xsl:when test>, <xsl:otherwise> | multi-way conditional |
<xsl:variable name="n" select="..."/> | an immutable value, used as $n |
<xsl:param name="p" select="default"/> | a parameter that callers, or Java code, can set |
<xsl:text> | literal text, including exact whitespace |
<xsl:element>, <xsl:attribute> | computed element and attribute names or values |
<xsl:copy>, <xsl:copy-of select="..."/> | copy the current node (shallow) or a node set (deep) |
<xsl:call-template name="...">, <xsl:with-param> | call a named template like a function |
<xsl:key> and key() | indexes for fast lookups |
Beyond the XPath 1.0 functions, XSLT adds functions such as format-number, document (reading other XML documents), key, generate-id and current.
Remember that a stylesheet is XML, so < inside a test must be written as <, and > is usually written > for symmetry.
The identity template is the starting point for stylesheets that change only part of a document. It copies everything, and more specific templates override it for the nodes you want to change:
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
Running a transformation from Java
The simplest approach compiles the stylesheet into a Transformer and transforms a source into a result:
TransformerFactory factory = TransformerFactory.newInstance();
Transformer t = factory.newTransformer(new StreamSource(stylesheetFile));
t.transform(new StreamSource(inputFile), new StreamResult(outputFile));
Compiling a stylesheet is expensive, and a Transformer can't be shared among threads. For repeated use, compile once into Templates, which are thread-safe, and get a cheap Transformer per use:
Templates templates = factory.newTemplates(new StreamSource(stylesheetFile));
Transformer t = templates.newTransformer();
t.setParameter("minSalary", 45000); // sets <xsl:param name="minSalary">
t.transform(source, result);
setOutputProperty overrides the settings of xsl:output (article 46 used it with the identity transformation).
Sources and results
Source | Result |
|---|---|
StreamSource (file, stream, reader, system id) | StreamResult (file, stream, writer) |
DOMSource (any node) | DOMResult (fills a document or node) |
SAXSource (an XMLReader plus InputSource) | SAXResult (sends events to a ContentHandler) |
StAXSource (a stream or event reader) | StAXResult (a stream or event writer) |
A DOMResult lets you continue working with the output as a tree, without writing and re-parsing it.
SAXSource enables a clever trick: the input doesn't have to be XML at all. Any XMLReader that delivers SAX events will do. The demo's EmployeeReader reads a pipe-delimited text file and reports the events a parser would report for the corresponding XML (startElement("employee"), characters(...), and so on). The stylesheet can't tell the difference. Extending XMLFilterImpl and overriding parse is the shortest way to write such a reader, since the base class supplies the rest of the XMLReader interface.
Errors
Errors in the stylesheet raise a TransformerConfigurationException when it's compiled. Errors during the transformation raise a TransformerException. By default, the processor also prints messages to standard error. Install an ErrorListener on the factory and the transformer to handle them yourself.
XSLT and security
A stylesheet is a program. Running a stylesheet you don't trust is like running untrusted code, because XSLT can read files with document() and, through extension functions, call arbitrary Java methods. The JDK's defenses:
- Extension functions are disabled by default in recent JDKs (
jdk.xml.enableExtensionFunctions=falseinconf/jaxp.properties), as the demo's last line shows. factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)enforces the processing limits and also disables extension functions.factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "")andACCESS_EXTERNAL_STYLESHEETrestrict which protocols may be used to load DTDs, imported stylesheets anddocument()targets.
The input documents need the same protection as in article 40.
The program
The demo applies three compiled stylesheets to the employee data: one producing an HTML table, one producing properties-style text, and a report that uses for-each, sort, choose, if, attribute value templates and a parameter set from Java. It then feeds the text stylesheet a flat file through a fake XMLReader, captures a result in a DOM tree, and finally shows a stylesheet error and a blocked extension function.
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Solution {
static final String STAFF = """
<staff>
<employee>
<name>Ada Lovelace</name>
<salary>75000</salary>
<hiredate year="2019" month="12" day="15"/>
</employee>
<employee>
<name>Alan Turing</name>
<salary>50000</salary>
<hiredate year="2021" month="10" day="1"/>
</employee>
<employee>
<name>Grace & Co</name>
<salary>40000</salary>
<hiredate year="2024" month="3" day="15"/>
</employee>
</staff>""";
static final String TO_HTML = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="no"/>
<xsl:template match="/staff">
<table border="1"><xsl:apply-templates/></table>
</xsl:template>
<xsl:template match="/staff/employee">
<tr><xsl:apply-templates/></tr>
</xsl:template>
<xsl:template match="/staff/employee/name">
<td><xsl:apply-templates/></td>
</xsl:template>
<xsl:template match="/staff/employee/salary">
<td>$<xsl:apply-templates/></td>
</xsl:template>
<xsl:template match="/staff/employee/hiredate">
<td><xsl:value-of select="@year"/>-<xsl:value-of select="@month"/>-<xsl:value-of select="@day"/></td>
</xsl:template>
<xsl:template match="text()[normalize-space() = '']"/>
</xsl:stylesheet>""";
static final String TO_PROPERTIES = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" omit-xml-declaration="yes"/>
<xsl:template match="/staff/employee">
<xsl:variable name="n" select="count(preceding-sibling::employee) + 1"/>
employee.<xsl:value-of select="$n"/>.name=<xsl:value-of select="name"/>
employee.<xsl:value-of select="$n"/>.salary=<xsl:value-of select="salary"/>
employee.<xsl:value-of select="$n"/>.hiredate=<xsl:value-of select="concat(hiredate/@year, '-', format-number(hiredate/@month, '00'), '-', format-number(hiredate/@day, '00'))"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>""";
static final String REPORT = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:param name="minSalary" select="0"/>
<xsl:template match="/">
<report threshold="{$minSalary}" total="{format-number(sum(//salary), '#,##0')}">
<xsl:for-each select="staff/employee[salary >= $minSalary]">
<xsl:sort select="salary" data-type="number" order="ascending"/>
<person since="{hiredate/@year}">
<xsl:attribute name="band">
<xsl:choose>
<xsl:when test="salary >= 70000">senior</xsl:when>
<xsl:when test="salary >= 45000">mid</xsl:when>
<xsl:otherwise>junior</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:value-of select="name"/>
<xsl:if test="hiredate/@year >= 2024"> (new)</xsl:if>
</person>
</xsl:for-each>
</report>
</xsl:template>
</xsl:stylesheet>""";
/** Pretends to parse XML, but turns a pipe-delimited flat file into SAX events. */
static class EmployeeReader extends XMLFilterImpl {
@Override
public void parse(InputSource input) throws IOException, SAXException {
ContentHandler h = getContentHandler();
var none = new AttributesImpl();
var in = new BufferedReader(input.getCharacterStream());
h.startDocument();
h.startElement("", "staff", "staff", none);
String line;
while ((line = in.readLine()) != null) {
String[] f = line.split("\\|");
h.startElement("", "employee", "employee", none);
element(h, "name", f[0]);
element(h, "salary", f[1]);
var date = new AttributesImpl();
date.addAttribute("", "year", "year", "CDATA", f[2]);
date.addAttribute("", "month", "month", "CDATA", f[3]);
date.addAttribute("", "day", "day", "CDATA", f[4]);
h.startElement("", "hiredate", "hiredate", date);
h.endElement("", "hiredate", "hiredate");
h.endElement("", "employee", "employee");
}
h.endElement("", "staff", "staff");
h.endDocument();
}
static void element(ContentHandler h, String name, String text) throws SAXException {
h.startElement("", name, name, new AttributesImpl());
h.characters(text.toCharArray(), 0, text.length());
h.endElement("", name, name);
}
}
static StreamSource src(String s) { return new StreamSource(new StringReader(s)); }
static String run(Templates templates, Source input, Map<String, Object> params) throws TransformerException {
Transformer t = templates.newTransformer();
params.forEach(t::setParameter);
var out = new StringWriter();
t.transform(input, new StreamResult(out));
return out.toString();
}
public static void main(String[] args) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setErrorListener(new ErrorListener() { // report instead of printing to System.err
public void warning(TransformerException e) { }
public void error(TransformerException e) throws TransformerException { throw e; }
public void fatalError(TransformerException e) throws TransformerException { throw e; }
});
Templates html = factory.newTemplates(src(TO_HTML)); // compiled once, thread-safe
Templates props = factory.newTemplates(src(TO_PROPERTIES));
Templates report = factory.newTemplates(src(REPORT));
System.out.println("--- XML to HTML ---");
System.out.println(run(html, src(STAFF), Map.of()));
System.out.println("--- XML to text ---");
System.out.println(run(props, src(STAFF), Map.of()).strip());
System.out.println("--- for-each, sort, choose, parameters ---");
System.out.println(run(report, src(STAFF), Map.of()).strip());
System.out.println(run(report, src(STAFF), Map.of("minSalary", 45000)).strip());
System.out.println("--- a flat file as a SAX source ---");
String flat = """
Linus Pauling|61000|2018|7|4
Rosalind Franklin|83000|2016|2|28
""";
var saxSource = new SAXSource(new EmployeeReader(), new InputSource(new StringReader(flat)));
System.out.println(run(props, saxSource, Map.of()).strip());
System.out.println("--- result as a DOM tree ---");
Document target = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
report.newTransformer().transform(src(STAFF), new DOMResult(target));
NodeList people = target.getElementsByTagName("person");
for (int i = 0; i < people.getLength(); i++) {
var p = (Element) people.item(i);
System.out.println(p.getAttribute("band") + ": " + p.getTextContent().strip());
}
System.out.println("--- errors ---");
try {
factory.newTemplates(src("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>"
+ "<xsl:template match='/'><xsl:value-of select='count(('/></xsl:template></xsl:stylesheet>"));
} catch (TransformerConfigurationException e) {
System.out.println("bad stylesheet: " + e.getClass().getSimpleName());
}
try {
factory.newTemplates(src("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'"
+ " xmlns:rt='http://xml.apache.org/xalan/java/java.lang.Runtime'>"
+ "<xsl:template match='/'><xsl:value-of select=\"rt:getRuntime()\"/></xsl:template></xsl:stylesheet>"))
.newTransformer().transform(src("<x/>"), new StreamResult(new StringWriter()));
System.out.println("extension function ran");
} catch (TransformerException e) {
String m = String.valueOf(e.getMessage());
System.out.println("extension function blocked: " + m.replaceAll("http:\\S+", "...").replace("java.lang.RuntimeException: ", ""));
}
}
}
--- XML to HTML ---
<table border="1"><tr><td>Ada Lovelace</td><td>$75000</td><td>2019-12-15</td></tr><tr><td>Alan Turing</td><td>$50000</td><td>2021-10-1</td></tr><tr><td>Grace & Co</td><td>$40000</td><td>2024-3-15</td></tr></table>
--- XML to text ---
employee.1.name=Ada Lovelace
employee.1.salary=75000
employee.1.hiredate=2019-12-15
employee.2.name=Alan Turing
employee.2.salary=50000
employee.2.hiredate=2021-10-01
employee.3.name=Grace & Co
employee.3.salary=40000
employee.3.hiredate=2024-03-15
--- for-each, sort, choose, parameters ---
<report threshold="0" total="165,000">
<person since="2024" band="junior">Grace & Co (new)</person>
<person since="2021" band="mid">Alan Turing</person>
<person since="2019" band="senior">Ada Lovelace</person>
</report>
<report threshold="45000" total="165,000">
<person since="2021" band="mid">Alan Turing</person>
<person since="2019" band="senior">Ada Lovelace</person>
</report>
--- a flat file as a SAX source ---
employee.1.name=Linus Pauling
employee.1.salary=61000
employee.1.hiredate=2018-07-04
employee.2.name=Rosalind Franklin
employee.2.salary=83000
employee.2.hiredate=2016-02-28
--- result as a DOM tree ---
junior: Grace & Co (new)
mid: Alan Turing
senior: Ada Lovelace
--- errors ---
bad stylesheet: TransformerConfigurationException
extension function blocked: Use of the extension function '... is not allowed when extension functions are disabled by the secure processing feature or the property 'jdk.xml.enableExtensionFunctions'. To enable extension functions, set 'jdk.xml.enableExtensionFunctions' to 'true'.
Notice that the HTML output escaped the ampersand, while the text output didn't. The format-number(..., '00') call pads the months and days in the text version.
Common questions
Can I use XSLT 2.0 or 3.0 features such as xsl:for-each-group or regular expressions?
Not with the JDK's built-in processor, which implements XSLT 1.0. Add Saxon-HE (open source) and select it with TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null) or the javax.xml.transform.TransformerFactory system property. Your Java code stays the same.
How do I group items in XSLT 1.0?
Use the "Muenchian method": declare <xsl:key name="byDept" match="employee" use="dept"/>, then iterate the first item of each group with employee[generate-id() = generate-id(key('byDept', dept)[1])] and process key('byDept', dept) inside.
Can I pass a Java object or several values as a parameter?
setParameter accepts strings, numbers, booleans and DOM nodes or node lists. Pass a Node to give the stylesheet a document to navigate, or pass simple values separately. Declare each parameter with <xsl:param name="..."/> at top level.
How do I output a or other HTML entities?
XML doesn't know . Write the character itself ( ) in the stylesheet; the JDK's html output method prints it as . To output < or & literally in text output, use method="text".
Is XSLT still worth learning? It's niche today, but it shows up in document publishing (DocBook, DITA), report generation, legacy enterprise integration and XML-based configuration. For transforming JSON or object data, ordinary Java code or templating engines are more common choices.
API reference
| API | Purpose |
|---|---|
TransformerFactory.newInstance() | the XSLT processor factory |
factory.newTransformer(Source xsl) | compile and get a transformer in one step |
factory.newTemplates(Source xsl) | compile a reusable, thread-safe stylesheet |
Templates.newTransformer() | transformer for one thread |
Transformer.transform(Source, Result) | run the transformation |
Transformer.setParameter(name, value) | set an xsl:param |
Transformer.setOutputProperty(name, value) | override xsl:output settings |
factory.setErrorListener(listener) | handle compile and run-time messages |
StreamSource, DOMSource, SAXSource, StAXSource | inputs |
StreamResult, DOMResult, SAXResult, StAXResult | outputs |
XMLFilterImpl | convenient base for a custom XMLReader |
XMLConstants.FEATURE_SECURE_PROCESSING, ACCESS_EXTERNAL_STYLESHEET | security settings |
Summary
- XSLT stylesheets declare templates whose
matchpatterns select input nodes and whose bodies describe the output. apply-templatesrecursively processes children, and built-in rules copy text and descend into elements. Suppress unwanted text with empty templates.value-of, attribute value templates{...},for-each,sort,if,choose, variables and parameters cover most transformations.- In Java, compile stylesheets into thread-safe
Templates, then use aTransformerper thread to transform anySourceinto anyResult. - A
SAXSourcewith a customXMLReadercan present non-XML data as XML. - Treat stylesheets as code. Keep extension functions disabled and restrict external access.
Practice Questions
Without any templates of your own, what does an XSLT processor output for an XML document?
The built-in rules apply: elements produce nothing themselves but their children are processed, and text nodes are copied. So the output is all the text content of the document concatenated, including the whitespace between elements, without any tags.
Write a template that outputs every employee name on its own line, in alphabetical order, as plain text.
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:for-each select="staff/employee">
<xsl:sort select="name"/>
<xsl:value-of select="name"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
Why should a web server compile its stylesheet into a Templates object instead of calling newTransformer(stylesheet) per request?
Compiling the stylesheet is the expensive step. Templates holds the compiled form and is thread-safe, so it can be created once and shared. Each request then calls templates.newTransformer(), which is cheap. A Transformer itself isn't thread-safe and shouldn't be shared between concurrent requests.
How can you run an XSLT stylesheet over data from a CSV file without first writing an XML file?
Write an XMLReader, for example by extending XMLFilterImpl and overriding parse, that reads the CSV and calls startElement, characters and endElement on its content handler as if it had parsed the equivalent XML. Wrap it in a SAXSource and pass that to transform.
Users may upload their own stylesheets to format reports. What are the risks, and how do you reduce them?
A stylesheet can call Java methods through extension functions, read local files or internal URLs with document() or imports, and consume excessive resources. Keep extension functions disabled (the default in recent JDKs; also FEATURE_SECURE_PROCESSING), set ACCESS_EXTERNAL_STYLESHEET and ACCESS_EXTERNAL_DTD to the empty string, keep the processing limits, and ideally run untrusted transformations in an isolated process with time and memory limits.
Previous: Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX
Next: Java Sockets: Connecting to a Server, Timeouts and InetAddress
Related reading
- Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX
- Streaming XML Parsers in Java: SAX and StAX
- XML Namespaces: Prefixes, Default Namespaces and Namespace-Aware Parsing
- Querying XML with XPath: Expressions and the XPath API
- Validating XML with XML Schema: Types, Sequences and a Practical Example

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.