StAX XML formatting in Java
There is com.sun.xml.txw2.output.IndentingXMLStreamWriter
XMLOutputFactory xmlof = XMLOutputFactory.newInstance();XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
Via the JDK: transformer.setOutputProperty(OutputKeys.INDENT, "yes");
.
Using the JDK Transformer:
public String transform(String xml) throws XMLStreamException, TransformerException{ Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Writer out = new StringWriter(); t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out)); return out.toString();}