Formats an XML string to pretty print it. - Java XML

Java examples for XML:XML Transform

Description

Formats an XML string to pretty print it.

Demo Code


//package com.java2s;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
    public static void main(String[] argv) throws Exception {
        String input = "java2s.com";
        int indent = 2;
        System.out.println(formatXML(input, indent));
    }//from  ww w .  ja v a2  s  .  c  o  m

    /**
     * Formats an XML string to pretty print it.
     * 
     * @param input the input XML string.
     * @param indent the indent characters for the output XML string.
     * @return an XML string indented.
     */
    public static String formatXML(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();
            transformerFactory.setAttribute("indent-number", indent);
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials