pretty Print XML String - Android XML

Android examples for XML:XML String

Description

pretty Print XML String

Demo Code

/*/*from  www  . jav  a  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.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
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";
    System.out.println(prettyPrint(input));
  }

  private static Transformer normalizerTransformer = null;
  private static Transformer serializerTransformer = null;

  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) {
      }
    }

    return input;
  }
}

Related Tutorials