Java: Writing a DOM to an XML file (formatting issues)
Asked Answered
S

3

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?

Succentor answered 2/10, 2008 at 9:10 Comment(1)
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.Photoneutron
A
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");
Antevert answered 2/10, 2008 at 9:18 Comment(2)
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);Dehydrate
Cheers @Dehydrate that managed to fix the issues I was havingSpaceship
D
17
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

source How to pretty print XML from Java?

Defalcation answered 2/5, 2012 at 11:14 Comment(0)
F
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

Florez answered 17/11, 2008 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.