Transforms a DOM into the bytes of a utf-8 string - Java XML

Java examples for XML:XSLT

Description

Transforms a DOM into the bytes of a utf-8 string

Demo Code


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 static Logger log = Logger.getLogger(DomUtil.class);
    /**************************************************************************
     ************                  Private Methods           ******************
     *************************************************************************/
    //    private static TransformerFactory transFact = TransformerFactory.newInstance();
    private static TransformerFactory transFact = TransformerFactory
            .newInstance();/* ww w . j a  v a 2  s.  c om*/
    /** Transforms a DOM into the bytes of a utf-8 string
     * @param doc a DOM Document
     * @param withXmlDeclaration include the xml declaration?
     * @return byte[] representation of the DOM
     */
    public static byte[] domToBytes(Node doc, boolean withXmlDeclaration) {
        try {
            //            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = transFact.newTransformer();
            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) {
            // Use the contained exception, if any
            Throwable x = tce;
            if (tce.getException() != null)
                x = tce.getException();
            x.printStackTrace();
            log.error(x);
        } catch (TransformerException te) {
            // Use the contained exception, if any
            Throwable x = te;
            if (te.getException() != null)
                x = te.getException();
            x.printStackTrace();
            log.error(x);
        }
        return null;
    }
}

Related Tutorials