Java XML Format prettyPrintXml(String input)

Here you can find the source of prettyPrintXml(String input)

Description

pretty Print Xml

License

Open Source License

Declaration

public static String prettyPrintXml(String input) throws Exception 

Method Source Code

//package com.java2s;
/*/*www  .j a  va  2  s  .c  o m*/
 * Copyright (c) Mirth Corporation. All rights reserved.
 * 
 * http://www.mirthcorp.com
 * 
 * The software in this package is published under the terms of the MPL license a copy of which has
 * been included with this distribution in the LICENSE.txt file.
 */

import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Main {
    public static String prettyPrintXml(String input) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        documentBuilderFactory.setValidating(false);
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(
                new StringReader(input)));
        Element element = document.getDocumentElement();
        element.normalize();

        Writer writer = new StringWriter();
        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("indent-number", new Integer(4));
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(new DOMSource(element), new StreamResult(
                writer));
        return writer.toString();
    }
}

Related

  1. prettyFormatXmlText(String text)
  2. prettyPrint(final Source source)
  3. prettyPrint(String header, String xml)
  4. prettyPrintToString(String xml)
  5. prettyPrintXml(SOAPMessage message)
  6. prettyPrintXml(String input)
  7. prettyPrintXML(String xml)
  8. prettyXml(final String xml)
  9. prettyXml(String xml)