Java XML Format prettifyString(String string)

Here you can find the source of prettifyString(String string)

Description

Returns a prettified version of the string, or the original string if the operation is not possible.

License

Open Source License

Declaration

public static String prettifyString(String string) 

Method Source Code


//package com.java2s;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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  ww w . jav a  2s .c  om*/
     * Returns a prettified version of the string, or the original
     * string if the operation is not possible.
     */
    public static String prettifyString(String string) {
        String result = string;
        if (string.startsWith("<?xml")) {
            result = prettifyXML(string);
        }
        return result;
    }

    /**
     * Returns a prettified version of the XML, with indentations and
     * linefeeds.  Returns the original string if there was an error.
     */
    public static String prettifyXML(String xml) {
        String result = xml;
        try {
            StringReader reader = new StringReader(xml);
            StringWriter writer = new StringWriter();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(new StreamSource(reader), new StreamResult(writer));
            writer.close();

            result = writer.toString();
        } catch (TransformerFactoryConfigurationError error) {
            // Ignore.
        } catch (TransformerException error) {
            // Ignore.
        } catch (IOException error) {
            // Ignore.
        }
        return result;
    }
}

Related

  1. formatXml(String xml)
  2. formatXML(String xml)
  3. formatXml(String xml)
  4. formatXML(Transformer transformer)
  5. formatXMLStr(String xml)
  6. prettyFormat(String input)
  7. prettyFormat(String input)
  8. prettyFormat(String input)
  9. prettyFormat(String input, int indent)