如何强制java xml dom在<?xml version ="1.0"encoding ="UTF-8"之后生成换行符?>?

Ste*_*nko 10 java xml formatting dom

我使用此代码启用换行符:

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

但我得到以下输出:

<?xml version="1.0" encoding="UTF-8"?><root>
  <child>aaaa</child>
</root>
Run Code Online (Sandbox Code Playgroud)

我想在root元素之前有换行符.我该怎么办?

Vik*_*ury 5

尝试这个

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

  • 它对我不起作用。将 `doc.appendChild(doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"myStylesheet.xsl\""));` 放在 root 创建之前,` 之前没有换行符&lt;root&gt;` 并且此解决方案不起作用。 (2认同)