XSLTransformer.java - XML Transformer
<< XSL (Extensible Stylesheet Language)
<< JDK (Java Development Kit) Tutorials
This section provides a tutorial example on how to write an XML transformer program, XSLTransformer.java, using XSL (Extensible Stylesheet Language).
Here is my first XML transformation program using XSL (Extensible Stylesheet Language): XSLTransformer.java:
/** * XSLTransformer.java * Copyright (c) 2002 by Dr. Herong Yang */ 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 template file that contains the transformation style rules:
<?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>
Run "java XSLTransformer hello.xml hello.out hello.xsl", I got in hello.out:
<?xml version="1.0" encoding="UTF-8"?> Hello world! - From hello.xsl.
The result shows that my XML file has been transformed correctly.
Last update: 2006.
Sections in This Chapter
XSL (Extensible Stylesheet Language) - Implementation in JDK