Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Node; public class Main { /** * Gets the node as raw. * * @param pNode * the p node * @param encoding * the encoding * @param pRemoveXmlLine * the p remove xml line * @return the node as raw * @throws Exception * the exception */ public static byte[] getNodeAsRaw(Node pNode, String encoding, boolean pRemoveXmlLine) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(outputStream); transformNode(pNode, encoding, pRemoveXmlLine, result); return outputStream.toByteArray(); } /** * Transform node. * * @param node * the node * @param encoding * the encoding * @param removeXmlHeader * the remove xml header * @param result * the result * @throws Exception * the exception */ private static void transformNode(Node node, String encoding, boolean removeXmlHeader, StreamResult result) throws Exception { TransformerFactory transformerFactory = null; Transformer transformer = null; DOMSource source = null; try { transformerFactory = TransformerFactory.newInstance(); if (transformerFactory == null) { throw new Exception("TransformerFactory error"); } transformer = transformerFactory.newTransformer(); if (transformer == null) { throw new Exception("Transformer error"); } transformer.setOutputProperty(OutputKeys.ENCODING, encoding); if (removeXmlHeader) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } else { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } source = new DOMSource(node); transformer.transform(source, result); } catch (TransformerFactoryConfigurationError e) { throw new Exception("TransformerFactoryConfigurationError", e); } catch (TransformerConfigurationException e) { throw new Exception("TransformerConfigurationException", e); } catch (TransformerException e) { throw new Exception("TransformerException", e); } } }