pretty Print XML Document via Transformer - Java XML

Java examples for XML:DOM Document

Description

pretty Print XML Document via Transformer

Demo Code

/*/*from   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 java.util.Hashtable;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String input = "java2s.com";
        System.out.println(prettyPrint(input));
    }
    private static Transformer normalizerTransformer = null;
    private static Transformer serializerTransformer = null;
    private static Logger logger = Logger.getLogger(XmlUtil.class);
    public static String prettyPrint(String input) {
        if ((normalizerTransformer != null)
                && (serializerTransformer != null)) {
            try {
                Source source = new StreamSource(new StringReader(input));
                Writer writer = new StringWriter();

                /*
                 * Due to a problem with the indentation algorithm of Xalan, we
                 * need to normalize the spaces first.
                 */

                // First, pre-process the xml to normalize the spaces
                DOMResult result = new DOMResult();
                normalizerTransformer.transform(source, result);
                source = new DOMSource(result.getNode());

                // Then, re-indent it
                serializerTransformer.transform(source, new StreamResult(
                        writer));

                return writer.toString();
            } catch (TransformerException e) {
                logger.error("Error pretty printing xml.", e);
            }
        }

        return input;
    }
}

Related Tutorials