How to add a carriage return to XML output in Java

Doug picture Doug · Nov 10, 2011 · Viewed 11.3k times · Source

In Java how do I output a carriage return in the resulting XML file, so that everything isn't on one line?

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("requests");
doc.appendChild(root);
root.appendChild(request);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);

The above code creates an XML file, but all on one line.

Answer

Zernike picture Zernike · Nov 10, 2011
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

First line add indents, second set indent value.