public static String formatXMLContent(final String message) { try { final InputSource src = new InputSource(new StringReader(message)); final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement(); final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSOutput lso = impl.createLSOutput(); lso.setEncoding("UTF-8"); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); writer.getDomConfig().setParameter("xml-declaration", true); StringWriter swr = new StringWriter(); lso.setCharacterStream(swr); writer.write(document, lso); return swr.toString(); } catch (Exception e) { e.printStackTrace(); return message; } }
more sample:
http://kveeresham.blogspot.com/2015/03/format-xml-using-java.html