Java XML Format prettyPrintXml(String input)

Here you can find the source of prettyPrintXml(String input)

Description

pretty Print Xml

License

Open Source License

Declaration

public static String prettyPrintXml(String input) 

Method Source Code


//package com.java2s;
/*//from   ww  w  .  j  a  v a2 s  .  c  o m
 * Copyright (C) 2005-2012 BetaCONCEPT Limited
 *
 * This file is part of Astroboa.
 *
 * Astroboa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Astroboa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Astroboa.  If not, see <http://www.gnu.org/licenses/>.
 */

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 String prettyPrintXml(String input) {

        if (input == null) {
            return "";
        }

        int indent = 2;

        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Exception e) {
            return input;
        }
    }
}

Related

  1. prettyPrint(final Source source)
  2. prettyPrint(String header, String xml)
  3. prettyPrintToString(String xml)
  4. prettyPrintXml(SOAPMessage message)
  5. prettyPrintXml(String input)
  6. prettyPrintXML(String xml)
  7. prettyXml(final String xml)
  8. prettyXml(String xml)
  9. prettyXml(String xml)