CSci 4608 Principles of Web Programming: XSL processing

This example shows how to process an XML file using XSL. In the example the output goes to standard output (System.out), but you can also direct it to the output of a servlet (the PrintWriter object of HttpResponse).


public class XSLProcessing {
    // this example illustrates how XSL transformations
    // can be done directly in the Java program
    // Both .xml and .xsl files are in the same directory 
    // as the program
    // The output is written to the standard output, 
    // but by setting the Result object one can direct
    // the output to the PrintWriter of an HttpResponse 
    // in a servlet

    public static void main(String [] args) 
    throws javax.xml.transform.TransformerException {
	String XMLSource = "food.xml";
	String XSLStylesheet = "food.xsl";
	// Instantiate a TransformerFactory.
	javax.xml.transform.TransformerFactory tFactory = 

	// Use the TransformerFactory to process the stylesheet Source and
	// generate a Transformer.
	javax.xml.transform.Transformer transformer = tFactory.newTransformer

	// Use the Transformer to transform an XML Source and send the
	// output to a Result object.

The XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="example1.xsl" ?>
<breakfast_menu xmlns:xsi=""
<food category="new">
<name>Belgian Waffles</name>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<name>Strawberry Belgian Waffles</name>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<food category="new">
<name>Berry-Berry Belgian Waffles</name>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<food category="traditional">
<name>French Toast</name>
<description>thick slices made from our homemade sourdough bread</description>
<name>Homestyle Breakfast</name>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>

The xsl file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited with XML Spy v4.2 -->
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:variable name="color">lightgreen</xsl:variable>
<xsl:template match="/breakfast_menu">
    <xsl:for-each select="food[@category='new']">
    <td BGCOLOR="{$color}"><xsl:value-of select="*[1]"/></td>
    <td><xsl:value-of select="*[2]"/></td>
    <td><xsl:value-of select="*[3]"/></td>
    <td><xsl:value-of select="*[4]"/></td>

CSci 2101 home page

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.