Java tutorial
//package com.java2s; import java.io.StringReader; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; public class Main { private static TransformerFactory transformerFactory; private static Transformer defaultTransformer; /** * Transforms the input XML document using the given XSLT content. */ public static Document transformDocWithXslt(Document document, String xsltContent) throws TransformerConfigurationException, TransformerException { Transformer transformer = getTransformerFromText(xsltContent); return transformToDomResult(document, transformer); } private static Transformer getTransformerFromText(String xsltContent) throws TransformerConfigurationException { if (xsltContent == null) { return getDefaultTransformer(); } else { checkTransformFactory(); return transformerFactory.newTransformer(new StreamSource(new StringReader(xsltContent))); } } private static Document transformToDomResult(Document document, Transformer transformer) throws TransformerConfigurationException, TransformerException { DOMResult domResult = new DOMResult(); synchronized (transformer) { transformer.transform(new DOMSource(document), domResult); } Document transformedDocument = (Document) domResult.getNode(); return transformedDocument; } private static Transformer getDefaultTransformer() throws TransformerConfigurationException { checkTransformFactory(); if (defaultTransformer == null) { defaultTransformer = transformerFactory.newTransformer(); } return defaultTransformer; } private static void checkTransformFactory() throws TransformerConfigurationException { if (transformerFactory == null) { transformerFactory = TransformerFactory.newInstance(); } } }