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) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //Set saxon as transformer.
        System.setProperty("javax.xml.transform.TransformerFactory",
                           "net.sf.saxon.TransformerFactoryImpl");

        simpleTransform("d:/project/hob/AppModule.xml",
                        "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!

3 comments:

  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
    John

    ReplyDelete
  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.

    ReplyDelete