Example usage for javax.xml.transform Transformer setOutputProperty

List of usage examples for javax.xml.transform Transformer setOutputProperty

Introduction

In this page you can find the example usage for javax.xml.transform Transformer setOutputProperty.

Prototype

public abstract void setOutputProperty(String name, String value) throws IllegalArgumentException;

Source Link

Document

Set an output property that will be in effect for the transformation.

Usage

From source file:Main.java

public static void prettyPrintXml(Document doc, OutputStream out, int indent) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // set indent spaces on factory
    //        tfactory.setAttribute("indent-number", new Integer(indent));

    try {/*from   w  w  w.  j av a 2 s  . c om*/
        Transformer serializer = tfactory.newTransformer();

        // turn on indenting on transformer (serializer)
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                //                  String.valueOf(indent));
                "2");

        serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "utf-8")));
    } catch (Exception e) {

        // this is fatal, just dump stack and throw runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Transform a org.w3c.dom.Node to a String
 * @param node - the Node//from w w  w.  j  a  va  2 s .c om
 * @param omitXmlDeclaration - omit XML declaration
 * @param prettyPrint - apply indentation
 * @return the String result
 * @throws TransformerException
 */
public static String elementToString(Node node, boolean omitXmlDeclaration, boolean prettyPrint) {
    String result = null;
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        if (omitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        if (prettyPrint) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        result = buffer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:br.gov.lexml.parser.documentoarticulado.LexMLUtil.java

public static String formatLexML(String xml) {
    String retorno = null;//www .j av  a  2s  . com
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);

        retorno = stringWriter.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return retorno;

}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {/*from  w  w w . ja  va2  s .co  m*/
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

From source file:com.iflytek.spider.util.DomUtil.java

/**
 * save dom into ouputstream/*  w w w. java  2  s . c o  m*/
 * 
 * @param os
 * @param e
 */
public static void saveDom(OutputStream os, Element e) {

    DOMSource source = new DOMSource(e);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(os);
        transformer.transform(source, result);
        os.flush();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (IOException e1) {
        e1.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (TransformerConfigurationException e2) {
        e2.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (TransformerException ex) {
        ex.printStackTrace(LogUtil.getWarnStream(LOG));
    }
}

From source file:net.bpelunit.framework.control.util.BPELUnitUtil.java

private static String serializeXML(Node node) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    ByteArrayOutputStream bOS = new ByteArrayOutputStream();
    t.transform(new DOMSource(node), new StreamResult(bOS));
    return bOS.toString();
}

From source file:Main.java

/**
 * Print XML in "pretty" format./* w ww .  j a v  a 2  s  .co  m*/
 * 
 * @param in an XML input stream
 * @param out where the result will go
 * @param indent the number of characters to indent
 */
public static void prettyPrintXml(InputStream in, OutputStream out, int indent) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // set indent spaces on factory
    //        tfactory.setAttribute("indent-number", new Integer(indent));

    try {
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(in);
        Transformer serializer = tfactory.newTransformer();

        // turn on indenting on transformer (serializer)
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                //                  String.valueOf(indent));
                "2");

        serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "utf-8")));
    } catch (Exception e) {

        // this is fatal, just dump stack and throw runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}

From source file:uk.ac.diamond.shibbolethecpauthclient.Utils.java

/**
 * Helper method that turns the message into a formatted XML string.
 * /*from   w  ww . j  a  v a2 s  . c  o m*/
 * @param doc
 *The XML document to turn into a formatted XML string
 * 
 * @return The XML string
 */
static String xmlToString(Element doc) {

    StringWriter sw = new StringWriter();
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:Main.java

public static void prettyPrint(Document document) {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;
    try {//  w  ww. java  2  s .  c  o  m
        serializer = tfactory.newTransformer();
        // Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        serializer.transform(new DOMSource(document), new StreamResult(System.out));
    } catch (TransformerException e) {
        // this is fatal, just dump the stack and throw a runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}

From source file:com.cuubez.visualizer.processor.ConfigurationProcessor.java

private static String getDocumentAsString(Document doc)
        throws TransformerFactoryConfigurationError, TransformerException {

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);

    return result.getWriter().toString();
}