Java:将DOM写入XML文件(格式问题) [英] Java: Writing a DOM to an XML file (formatting issues)
问题描述
我使用 org.w3c
XML API
来打开现有的 XML
文件。我正在删除一些节点,而我正在添加其他节点。
I'm using org.w3c
XML API
to open an existing XML
file. I'm removing some nodes , and I'm adding others instead.
问题是添加的新节点是一个接一个写的,没有换行符并没有缩进什么如此。虽然确实 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.
是有无论如何添加缩进,或每个节点之后至少一个换行符?
Is there anyway to add indentation , or at least a newline after each node?
推荐答案
我假设你正在使用 Transformer
来做实际的写作(对 StreamResult
)。在这种情况下,请在调用 transform
:
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");
这篇关于Java:将DOM写入XML文件(格式问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!