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.
This should fix the issue.
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
First line add indents, second set indent value.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With