views:

2391

answers:

3

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 another , 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 examnine it. Is there anyway to add indentation , or at least a newline after each node ?

+7  A: 

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");
Chris Jester-Young
Glad to be of help!
Chris Jester-Young
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
A: 

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

mlo55
A: 

Thanx Chris. I think the important part is the Line

tFactory.setAttribute("indent-number", 2);

Took me some time till I found your answer right here. Bug seems to be quite resistant. My Java Version: java.version=1.6.0_20

B runo E berhard