Java XML Format prettyFormatXmlText(String text)

Here you can find the source of prettyFormatXmlText(String text)

Description

Format the xml-text string in a human-readable fashion.

License

Open Source License

Parameter

Parameter Description
text xml-document text

Exception

Parameter Description
TransformerException an exception

Return

formatted xml-document

Declaration

public static String prettyFormatXmlText(String text) throws TransformerException 

Method Source Code

//package com.java2s;
/**//from w  w w . j ava  2  s  . com
 * Copyright (C) 2013 Inera AB (http://www.inera.se)
 *
 * This file is part of Inera MessageService (http://code.google.com/p/inera-message).
 *
 * Inera MessageService is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Inera MessageService 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.*;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
    /**
     * Format the xml-text string in a human-readable fashion.
     *
     * @param text xml-document text
     * @return formatted xml-document
     * @throws TransformerException
     */
    public static String prettyFormatXmlText(String text) throws TransformerException {
        // Instantiate transformer input
        Source xmlInput = new StreamSource(new StringReader(text));
        StreamResult xmlOutput = new StreamResult(new StringWriter());

        // Configure transformer
        Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity transformer
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);

        return xmlOutput.getWriter().toString();
    }
}

Related

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