简体   繁体   中英

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.

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

First line add indents, second set indent value.

这应该解决问题。

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM