Java XML Format prettyFormat(String input)

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

Description

pretty Format

License

Apache License

Declaration

public static String prettyFormat(String input) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import javax.xml.transform.*;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;

public class Main {
    public static String prettyFormat(String input, int indent, boolean isOmitXmlDeclaration) {
        try {/*w w  w.java  2 s . com*/
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setAttribute("indent-number", indent);
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            if (isOmitXmlDeclaration) {
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            }
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Exception e) {
            throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    public static String prettyFormat(String input) {
        return prettyFormat(input, 2, true);
    }
}

Related

  1. formatXml(String xml)
  2. formatXML(String xml)
  3. formatXML(Transformer transformer)
  4. formatXMLStr(String xml)
  5. prettifyString(String string)
  6. prettyFormat(String input)
  7. prettyFormat(String input)
  8. prettyFormat(String input, int indent)
  9. prettyFormat(String strInput, int nIndent)