Basic translator functions to translate from bytestream in to XML and vice versa.
/** * Class implementing the basic translator functions to translate from * bytestream in to XML and vice versa. * */ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public final class XmlTranslator { private XmlTranslator() { // private constructor - all methods are static } /** * Method to translate the given bytestream to an XML document. * * @param byte[] input byte stream to be translated * @return Document * @throws IOException * @throws SAXException * @throws SAXParseException * @throws ParserConfigurationException */ public static Document translate(byte[] byteStream) throws SAXParseException, SAXException, IOException, ParserConfigurationException { // Create an input stream ByteArrayInputStream xmlBytes = new ByteArrayInputStream(byteStream); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder(); Document newDoc = documentBuilder.parse(xmlBytes); xmlBytes.close(); return newDoc; } /** * Method to translate the given document to a byte stream * * @param Document document to be translated * @return byte[] * @throws IOException */ public static byte[] translate(Document document) throws IOException { return translate(document, false); } public static byte[] translate(Document document, boolean pretty) throws IOException { // Serialize DOM OutputFormat format = new OutputFormat(document, "UTF-8", true); StringWriter stringOut = new StringWriter(); // As DOM serializer XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); serial.serialize(document.getDocumentElement()); byte[] bytesOut = stringOut.toString().getBytes(); return bytesOut; } }