Tuesday, March 15, 2011

Saxon XSLT Java example

I was looking for simple Saxon XSLT transformation example using Java and I could not find one that is simple and descriptive enough, so I made one and I hope it will helpful for someone. So here it is :

import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {

     * Simple transformation method.
     * @param sourcePath - Absolute path to source xml file.
     * @param xsltPath - Absolute path to xslt file.
     * @param resultDir - Directory where you want to put resulting files.
    public static void simpleTransform(String sourcePath, String xsltPath,
                                       String resultDir) {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        try {
            Transformer transformer =
                tFactory.newTransformer(new StreamSource(new File(xsltPath)));

            transformer.transform(new StreamSource(new File(sourcePath)),
                                  new StreamResult(new File(resultDir)));
        } catch (Exception e) {

    public static void main(String[] args) {
        //Set saxon as transformer.

                        "d:/project/hob/create-fragment.xslt", "C:/");


You just need to put Saxon library into project CLASSPATH. This example create resulting file(s) on the root of C: drive.

Have fun!


  1. Can you tell me how to use this example..?
    I have XSL file named - sample.xsl
    I have XML file named - sample.xml
    I want output as html name - sample.html

    how to do this ..? along with setting the classpath..?

    Have a nice day

  2. Thanks, mate! In my case, it wanted a result file rather than a result directory, but it worked a treat as a base from which to start.

  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.