Java XML Format prettyPrintToString(String xml)

Here you can find the source of prettyPrintToString(String xml)

Description

pretty Print To String

License

Open Source License

Parameter

Parameter Description
xml a parameter

Declaration

public static String prettyPrintToString(String xml) 

Method Source Code

//package com.java2s;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */

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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
    /**//from w w  w. j  a  va  2 s  . co m
     * @param xml
     */
    public static String prettyPrintToString(String xml) {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        try {
            transformer.transform(xmlInput, xmlOutput);
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String formattedxml = xmlOutput.getWriter().toString();
        return formattedxml;

    }
}

Related

  1. prettyFormat(String strInput, int nIndent)
  2. prettyFormatXml(final InputStream xml, final OutputStream os, final int indent)
  3. prettyFormatXmlText(String text)
  4. prettyPrint(final Source source)
  5. prettyPrint(String header, String xml)
  6. prettyPrintXml(SOAPMessage message)
  7. prettyPrintXml(String input)
  8. prettyPrintXml(String input)
  9. prettyPrintXML(String xml)