Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.IOException; 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 { /** * Convert xml to byte array. * * @param pDocument * the p document * @param encoding * the encoding * @return the byte[] * @throws Exception * the exception */ public static byte[] convertXML2ByteArray(Node pDocument, String encoding) throws Exception { TransformerFactory transformerFactory = null; Transformer transformer = null; DOMSource domSource = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult result = null; try { transformerFactory = TransformerFactory.newInstance(); if (transformerFactory == null) { throw new Exception("TransformerFactory error"); } transformer = transformerFactory.newTransformer(); if (transformer == null) { throw new Exception("Transformer error"); } if (encoding != null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); } else { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } domSource = new DOMSource(pDocument); result = new StreamResult(outputStream); transformer.transform(domSource, result); return outputStream.toByteArray(); } catch (TransformerFactoryConfigurationError e) { throw new Exception("TransformerFactoryConfigurationError", e); } catch (TransformerConfigurationException e) { throw new Exception("TransformerConfigurationException", e); } catch (TransformerException e) { throw new Exception("TransformerException", e); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException ex) { throw new Exception("IO error", ex); } } } }