Java XML Format prettyPrint(final Source source)

Here you can find the source of prettyPrint(final Source source)

Description

Pretty print an XML.

License

Open Source License

Parameter

Parameter Description
source the XML source

Return

a String with readable XML

Declaration

public static String prettyPrint(final Source source) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 LegSem./*from  www. j a va2s  . c  o m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/

import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

public class Main {
    /**
     * Pretty print an XML. Use with caution as this drains the source if it is
     * a StreamSource.
     * @param source the XML source
     * @return a String with readable XML
     */
    public static String prettyPrint(final Source source) {
        try {
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            StringWriter writer = new StringWriter();
            serializer.transform(source, new StreamResult(writer));
            return writer.toString();
        } catch (TransformerException e) {
            return e.getMessage();
        }
    }
}

Related

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