27

I'm using org.w3c XML API to open an existing XML file. I'm removing some nodes , and I'm adding others instead.

The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the XML file is valid , it is very hard for a human to examine it.

Is there anyway to add indentation , or at least a newline after each node?

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Vhaerun
  • 12,806
  • 16
  • 39
  • 38
  • If you've come to this question looking for code examples for how to pretty print XML in Java then see [how to pretty print xml from Java](http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) instead. – George Hawkins May 04 '11 at 08:55

3 Answers3

54

I'm assuming that you're using a Transformer to do the actual writing (to a StreamResult). In which case, do this before you call transform:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 6
    BTW: in latest jdk there is a bug to get around this you will need to do before: TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", 2); – Karussell Feb 26 '10 at 13:01
  • Cheers @Karussell that managed to fix the issues I was having – Hayden Apr 09 '13 at 20:19
17
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

source How to pretty print XML from Java?

Community
  • 1
  • 1
Thilina
  • 171
  • 1
  • 2
1

There are a few good examples of "pretty printing" in the following thread

how to pretty print xml from Java

Link to my effort at a solution

Community
  • 1
  • 1
mlo55
  • 361
  • 2
  • 3