Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys INDENT.

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

From source file:XMLUtil.java

public static void write(Document doc, OutputStream out) throws IOException {
    // XXX note that this may fail to write out namespaces correctly if the
    // document//  www .  j a  v  a 2  s.co m
    // is created with namespaces and no explicit prefixes; however no code in
    // this package is likely to be doing so
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
        }
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N
        Source source = new DOMSource(doc);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception e) {
        throw (IOException) new IOException(e.toString()).initCause(e);
    } catch (TransformerFactoryConfigurationError e) {
        throw (IOException) new IOException(e.toString()).initCause(e);
    }
}

From source file:ru.retbansk.utils.UsefulMethods.java

/**
 * For testing usage. Take unformatted xml string. Return pretty readable xml string
 * /*from  w  w w .j a  va  2s.  co m*/
 * @param input take unformatted xml string
 * @param indent a number of white spaces before each line
 * @return pretty readable xml string
 */

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // This statement works with JDK 6
        transformerFactory.setAttribute("indent-number", indent);

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Throwable e) {
        // You'll come here if you are using JDK 1.5
        // you are getting an the following exeption
        // java.lang.IllegalArgumentException: Not supported: indent-number
        // Use this code (Set the output property in transformer.
        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Throwable t) {
            return input;
        }
    }
}

From source file:Main.java

private static void writeTo(Result result, Document document) throws TransformerConfigurationException,
        TransformerException, FileNotFoundException, UnsupportedEncodingException {

    // Use a Transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setAttribute("indent-number", new Integer(4));

    Transformer transformer = tFactory.newTransformer();
    DOMSource source = new DOMSource(document);

    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
    transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N

    // indent the output to make it more legible... 
    try {//  w  w w.j  av a2s .  c  om
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
    } catch (IllegalArgumentException e) {
        // the JAXP implementation doesn't support indentation, no big deal
        //e.printStackTrace();
    }

    transformer.transform(source, result);
}

From source file:Main.java

public static final String indenting(Node rootNode) throws XPathExpressionException, TransformerException {

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

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }/*from   w ww. ja  va 2 s  .c om*/

    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(rootNode), streamResult);

    return stringWriter.toString();
}

From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java

/**
 * @param items//from ww w .j  a v a 2 s  .  c  om
 * @return
 */
public static void convertToXml(OutputStream outputStream, Document dom) {
    Transformer transformer = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    } catch (TransformerConfigurationException e) {
        LOGGER.error(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        return;
    }
    try {
        transformer.transform(new DOMSource(dom), new StreamResult(outputStream));
    } catch (TransformerException e) {
        LOGGER.error("Transform failed with TransformerException: " + e.getMessage());
    }
}

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

public static String formatLexML(String xml) {
    String retorno = null;/*  w w  w.j  av a2  s .  c o m*/
    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:no.digipost.api.interceptors.SoapLog.java

private Transformer createNonIndentingTransformer() throws TransformerConfigurationException {
    Transformer transformer = createTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    return transformer;
}

From source file:com.mockey.storage.xml.MockeyXmlFactory.java

private String getDocumentAsString(Document document) throws IOException, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, HTTP.UTF_8);
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(document);
    transformer.transform(source, result);
    return result.getWriter().toString();
}

From source file:it.polito.tellmefirst.web.rest.interfaces.AbsResponseInterface.java

public TransformerHandler initXMLDoc(ByteArrayOutputStream out) throws TMFOutputException {
    LOG.debug("[initXMLDoc] - BEGIN");
    TransformerHandler hd;//w w w . j ava2 s. c o m
    try {
        StreamResult streamResult = new StreamResult(out);
        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        hd = tf.newTransformerHandler();
        Transformer serializer = hd.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        hd.setResult(streamResult);
        hd.startDocument();
    } catch (Exception e) {
        throw new TMFOutputException("Error initializing XML.", e);
    }
    LOG.debug("[initXMLDoc] - END");
    return hd;
}

From source file:com.konakart.bl.modules.ordertotal.thomson.HeaderLoggingHandler.java

/**
 * Outputs the soap msg to the logger//from w w w.  j a  v a  2s .c o m
 * 
 * @param context
 */
public void logSoapMsg(SOAPMessageContext context) {
    if (!log.isDebugEnabled()) {
        return;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    String msgType = null;
    if (outboundProperty.booleanValue()) {
        msgType = "Request:";
    } else {
        msgType = "Response:";
    }

    SOAPMessage message = context.getMessage();
    try {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();

        // Set formatting

        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Source sc = message.getSOAPPart().getContent();

        ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(streamOut);
        tf.transform(sc, result);

        if (log.isDebugEnabled()) {
            log.debug(msgType + "\n" + streamOut.toString()
                    + "\n------------------------------------------------------------------------");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}