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

时光总嘲笑我的痴心妄想 提交于 2019-12-03 06:42:30

问题


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?


回答1:


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");



回答2:


transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

source How to pretty print XML from Java?




回答3:


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



来源:https://stackoverflow.com/questions/161462/java-writing-a-dom-to-an-xml-file-formatting-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!