XSLTransformer.java - A Simple XSLT Transformation Program

This section provides a tutorial example on how to use the XSLT implementation in JDK 1.4 to write a simple XSLT transformation Java program.

Here is my first XSLT transformation program in Java:

/* XSLTransformer.java
 - Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
class XSLTransformer {
   public static void main(String[] args) {
      try {
         File sf = new File(args[0]); // source file
         File rf = new File(args[1]); // result file
         File tf = new File(args[2]); // template file
         TransformerFactory f = TransformerFactory.newInstance();
         Transformer t = f.newTransformer(new StreamSource(tf));
         Source s = new StreamSource(sf);
         Result r = new StreamResult(rf);
         t.transform(s,r);
      } catch (TransformerConfigurationException e) {
         System.out.println(e.toString());      
      } catch (TransformerException e) {
         System.out.println(e.toString());
      }
   }
}

Let's try this program with my hello.xml as the source file:

<?xml version="1.0"?>
<p>Hello world!</p>

and my hello.xsl as the stylesheet file that contains the transformation templates:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="p">Hello world.! - From hello.xsl.</xsl:template>
</xsl:stylesheet>

Compile and run XSLTransformer.java with JDK 1.8:

C:\herong\xml>java XSLTransformer hello.xml hello.out hello.xsl

C:\herong\xml>type hello.out
<?xml version="1.0" encoding="UTF-8"?>
Hello world! - From hello.xsl.

Cool. XSLTransformer.java is working!

Last update: 2014.

Table of Contents

 About This Book

 Introduction of XML (eXtensible Markup Language)

 XML File Syntax

 XML File Browsers

 DOM (Document Object Model) Programming Interface

 SAX (Simple API for XML) Programming Interface

 DTD (Document Type Definition) Introduction

 Syntaxes of DTD Statements

 Validating an XML Document against the Specified DTD Document Type

 XSD (XML Schema Definition) Introduction

 Syntaxes of XSD Statements

 Validating XML Documents Against Specified XML Schemas

 XSL (Extensible Stylesheet Language) Introduction

 XSLT (XSL Transformations) Introduction

Java Implementation of XSLT

 XSLT Implementations in JDK 1.4

XSLTransformer.java - A Simple XSLT Transformation Program

 XPath (XML Path) Language

 XSLT Elements as Programming Statements

 Control and Generate XML Element in the Result

 XML Notepad - XML Editor

 XML Tools Plugin for Notepad++

 XML 1.1 Changes and Parsing Examples

 Outdated Tutorials

 References

 PDF Printing Version