Java: Simple XSLT transformation without external libraries


Here's how to do a simple XSLT transformation using only classes in vanilla Java 1.5 (maybe even 1.4?), no external libraries or anything. The classes are found in the javax.xml.transform package.

// Create a factory
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXTransformerFactory.FEATURE))
    throw new RuntimeException("Did not find a SAX-compatible TransformerFactory.");
SAXTransformerFactory stf = (SAXTransformerFactory) tf;

// Create a reusable template for the XSLT
Templates xslt = stf.newTemplates(new SourceStream(inputStreamWithXslt));

// Use the template to transform some XML
    new StreamSource(inputStreamWithXml),
    new StreamResult(System.out)