11

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.

RobEarl
  • 7,862
  • 6
  • 35
  • 50
Doug
  • 6,446
  • 9
  • 74
  • 107
  • 1
    See if [this answer helps](http://stackoverflow.com/questions/6941826/java-1-6-javax-xml-transform-transformer-refuses-to-indent-xml-strings-which-co). – Dave Newton Nov 10 '11 at 19:19
  • 1
    Do you have a schema that you are using to base the XML off of? – ChadNC Nov 10 '11 at 19:36

3 Answers3

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

First line add indents, second set indent value.

Zernike
  • 1,758
  • 1
  • 16
  • 26
13

This should fix the issue.

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
skusunam
  • 411
  • 3
  • 12
  • 1
    while saving works as intended, loading the created file fails - how do you load an xml structure that has this output property. "com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element" – Schifty Jan 07 '13 at 14:05
  • 1
    Schifty, can you share your code so that people know the context you are talking and may be try out locally? – skusunam Jan 09 '13 at 17:25
1

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

finx
  • 1,293
  • 9
  • 9
  • 1
    Nice. In my case if I just edited existing xml and used the OutputProperty solution it could make some weird indents in the file. With this solution I can add newlines where ever I want in the xml. Thanks! I could also do my own indents with doc.createTextNode("\t"). – vilpe89 Sep 17 '19 at 15:49