【问题标题】:How to force java xml dom to produce newline after <?xml version="1.0" encoding="UTF-8"?>?如何在 <?xml version="1.0" encoding="UTF-8"?> 之后强制 java xml dom 生成换行符?
【发布时间】:2012-07-01 19:45:47
【问题描述】:

我使用这段代码来启用换行符:

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

但我得到以下输出:

<?xml version="1.0" encoding="UTF-8"?><root>
  <child>aaaa</child>
</root>

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

【问题讨论】:

    标签: java xml dom formatting


    【解决方案1】:

    试试这个

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

    【讨论】:

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

    另一个解决方案是: transformer.setOutputProperty(OutputKeys.INDENT, "是"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}缩进量", "10");

    【讨论】:

      【解决方案3】:

      其他答案对我不起作用,或者在我的申请中是不可接受的。这对我有用:

      transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
      

      【讨论】:

        【解决方案4】:

        您可以自己添加换行符,方法是将Writer 包装在FilterWriter(或OutputStream 中的FilterOutputStream)编码以识别该标签的结尾并在退出时添加换行符。

        但这有点傻。正如 Stephen C 在他的评论中指出的那样,您可能真的不应该在意这一点而烦恼。

        【讨论】:

          【解决方案5】:

          当声明后没有 DOCTYPE 或者您没有指定独立属性时,生成的 xml 文件往往会出现此问题。 如果您没有与文件相关的 DOCTYPE,请将独立属性设置为“是”。

          <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
          

          【讨论】:

            【解决方案6】:

            您可以手动插入换行符。将字符串分配给一个临时变量(假设它的 String temp)。然后做一些这样的事情

            String filteredStr = new StringBuilder(temp).insert(temp.indexOf('>') + 1, "\n")
                                .toString();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-10-13
              • 1970-01-01
              • 1970-01-01
              • 2016-06-11
              相关资源
              最近更新 更多