Java:将 DOM 写入 XML 文件(格式问题)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/161462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Writing a DOM to an XML file (formatting issues)
提问by Vhaerun
I'm using org.w3c
XML API
to open an existing XML
file. I'm removing some nodes , and I'm adding others instead.
我正在使用org.w3c
XML API
打开现有XML
文件。我正在删除一些节点,而我正在添加其他节点。
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.
问题是添加的新节点一个接一个地写入,没有换行符和缩进。虽然该XML
文件确实有效,但人类很难对其进行检查。
Is there anyway to add indentation , or at least a newline after each node?
无论如何要在每个节点后添加缩进或至少一个换行符?
采纳答案by Chris Jester-Young
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
:
我假设您正在使用 aTransformer
进行实际写作(到 a StreamResult
)。在这种情况下,请在调用之前执行此操作transform
:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
回答by mlo55
There are a few good examples of "pretty printing" in the following thread
以下线程中有一些“漂亮打印”的好例子
how to pretty print xml from Java
回答by Thilina
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
source How to pretty print XML from Java?
source 如何从 Java 漂亮地打印 XML?