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?

share|improve this question
    
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 instead. – George Hawkins May 4 '11 at 8:55
up vote 54 down vote accepted

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");
share|improve this answer
    
Glad to be of help! – Chris Jester-Young Oct 2 '08 at 9:25
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 9 '13 at 20:19
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

source How to pretty print XML from Java?

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.