Java examples for XML:XSLT
transform Dom To Bytes
import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.*; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main{ /************************************************************************** ************ Private Methods ****************** *************************************************************************/ // private static TransformerFactory transFact = TransformerFactory.newInstance(); private static TransformerFactory transFact = TransformerFactory .newInstance();/*from w ww . java 2 s .c o m*/ private static Map<String, Templates> templates = new HashMap<String, Templates>(); public static byte[] transformDomToBytes(Document doc, String stylesheet, boolean withXmlDeclaration, Map parameters) { try { // TransformerFactory tFactory = TransformerFactory.newInstance(); // StreamSource stylesource = new StreamSource(stylesheet); // Transformer transformer = tFactory.newTransformer(stylesource); Transformer transformer = getTransformer(stylesheet); transformer.clearParameters(); if (parameters != null) { for (Object o : parameters.keySet()) { String k = (String) o; transformer.setParameter(k, parameters.get(k)); } } if (!withXmlDeclaration) transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource source = new DOMSource(doc); ByteArrayOutputStream output = new ByteArrayOutputStream(); StreamResult result = new StreamResult(output); transformer.transform(source, result); return output.toByteArray(); } catch (TransformerConfigurationException tce) { Throwable x = tce; if (tce.getException() != null) x = tce.getException(); throw new RuntimeException(x); } catch (TransformerException te) { Throwable x = te; if (te.getException() != null) x = te.getException(); throw new RuntimeException(x); } } private static Transformer getTransformer(String xsltFile) throws TransformerConfigurationException { Templates tpl = (Templates) templates.get(xsltFile); if (tpl == null) { Source xsltSource = new StreamSource(xsltFile); tpl = transFact.newTemplates(xsltSource); if (tpl == null) { throw new RuntimeException("Stylesheet does not exist: " + xsltFile); } templates.put(xsltFile, tpl); } return tpl.newTransformer(); } }