This is a snippet of code to show how to perform an XSL transformation with Java

/** XSL Transform with input, output and parameters. */
@SuppressWarnings("unchecked")
public static void transform(Source xml, Source xsl, Result out, HashMap< String, ? > params){
  
    // factory init
    TransformerFactory factory = TransformerFactory.newInstance();
  
    // Transformer object init
    Transformer t;
    try {
        t = factory.newTransformer(xsl);
    } catch (TransformerConfigurationException e) {
        // if any XSL error
        throw new RuntimeException( ERR_XSL_CONFIGURATION, e );
    }
  
    // insert parameters (if any)
    if( params != null && params.size() > 0 ){
        Iterator< ? > i = params.entrySet().iterator();
        Entry< String, ? > me ;
        while(i.hasNext()){
            me = (Entry< String, ? >) i.next();
            t.setParameter(me.getKey(), me.getValue());
        }
    }
  
    // Transformation execution
    try {
        t.transform(xml, out);
    } catch (TransformerException e) {
        // if any Transformation error
        throw new RuntimeException( ERR_XSL_TRANSFORM, e );
    }
}

Below you can see how to XSL Transform using File, StreamSource and StreamResult.

// working dir
String uDir = System.getProperty("user.dir");
File baseDir = new File(uDir, "2011/xsl-to-xhtml");
File xmlFile = new File(baseDir, "books.xml");
File xslFile = new File(baseDir, "books.to.xhtml.xsl");
File outFile = new File(baseDir, "books.out.generated.xhtml");

// transform!
transform(new StreamSource(xmlFile), new StreamSource(xslFile), new StreamResult(outFile), null);

System.out.println("File generated: " + outFile);

And there it is an example of XSL Transform using StringReader and StringWriter.

String xmlData = "<books>"
 + "    <book isbn='1' title='Master XML' pdate='24/09/2010'/>"
 + "    <book isbn='2' title='Master Java' pdate='24/09/2010'/>"
 + "    <book isbn='3' title='Eclipse' pdate='21/09/2010'/>"
 + "</books>";

String xslStyle = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"
 + "    version='1.0'>"
 + "    <xsl:output method='xml' version='1.0' encoding='UTF-8' indent='yes'/>"
 + "    <xsl:template match='/books'>"
 + " <h1>Data</h1>"
 + " <xsl:for-each select='book' >"
 + " <xsl:value-of select='@title'/> ( <xsl:value-of select='@isbn'/> ) " + "<br/>"
 + " </xsl:for-each>"
 + "    </xsl:template>"
 + "</xsl:stylesheet>";

String out = "";

StringReader xmlRead = new StringReader(xmlData);
StringReader xslRead = new StringReader(xslStyle);
StringWriter outWriter = new StringWriter();

// transform!
transform(new StreamSource(xmlRead), new StreamSource(xslRead), new StreamResult(outWriter), null);

System.out.println(outWriter.toString());

Source code is available on my Git repository:

Categories: JavaXML

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *