简体   繁体   中英

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

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?

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");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

source How to pretty print XML from Java?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM