我有一个编辑xml文件的方法。该方法的一般概述如下:
public void process(Path anXmlFile) {
try {
anXmlFile= anXmlFile.normalize();
log.debug("processing {}",anXmlFile);
Document dom = buildDOM(anXmlFile.toFile());
//do stuff with dom...
//delete original file
//and finally ...
dom.normalize(); //so we get a more predictable order
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
Source source = new DOMSource(dom);
Result result = new StreamResult(anXmlFile.toFile());
transformer.transform(source, result);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
我的问题是,如果我在 XML 中有一个多行注释,它在某一行打开并在下一行关闭(注意换行符):
<!-- this is a long comment[cr][lf]
that spans 2 lines -->
然后,当我写出修改后的DOM时,结果将会是:
<!-- this is a long comment[cr]
that spans 2 lines -->
问题在于[回车][换行]变成了[回车]。这是XML中唯一受到此影响的部分。所有其他行尾都与原始行尾相同([回车][换行]) - 即使我修改了它们(我的代码不会更改DOM中的注释节点)。
是否有任何配置选项可以给我创建的Transformer,以避免这种情况?所有操作都使用JDK类完成,无涉及XML库。