Java XML Format prettyXml(String xml)

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

Description

pretty Xml

License

Apache License

Parameter

Parameter Description
xml a parameter

Return

pretty xml

Declaration

public static String prettyXml(String xml) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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 {
    /**//from   www .j  a  v a2s  .c  o  m
     * @param xml
     * @return pretty xml
     */
    public static String prettyXml(String xml) {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer serializer;
        try {
            Source source = new StreamSource(new StringReader(xml));
            StringWriter writer = new StringWriter();

            serializer = tfactory.newTransformer();
            // Setup indenting to "pretty print"
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            serializer.transform(source, new StreamResult(writer));
            return writer.toString();
        } catch (Exception e) {
            return xml;
        }
    }
}

Related

  1. prettyPrintXml(SOAPMessage message)
  2. prettyPrintXml(String input)
  3. prettyPrintXml(String input)
  4. prettyPrintXML(String xml)
  5. prettyXml(final String xml)
  6. prettyXml(String xml)
  7. prettyXml(String xml)
  8. prettyXmlPrint(Node xml, OutputStream out)
  9. print(Element elm, OutputStream out)