Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a carriage return to XML output in Java

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.

like image 983
Doug Avatar asked Nov 10 '11 19:11

Doug


3 Answers

This should fix the issue.

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
like image 114
skusunam Avatar answered Sep 29 '22 20:09

skusunam


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

First line add indents, second set indent value.

like image 45
Zernike Avatar answered Sep 29 '22 22:09

Zernike


After I spend some hours with this issue, finally I could solve the way I needed (to include a new line). The previous answers didn't work for me.

This way, I could include a new line: org.w3c.dom.Text nodeSeparator = doc.createTextNode("\n\n ");

And then, insert it before my desired node: parentNode.insertBefore(nodeSeparator, foundNode);

like image 36
finx Avatar answered Sep 29 '22 20:09

finx