【问题标题】:JAVA 8 xml pretty output not working properlyJAVA 8 xml 漂亮的输出无法正常工作
【发布时间】:2016-02-03 11:59:36
【问题描述】:

我尝试在漂亮的输出中将 Document 保存到 XML。但问题是每个新元素都从前一个元素结束标记的行开始。

例子:

<?xml version="1.0" encoding="UTF-8"?><report>
<jiraentry category="SERVICE &amp; ASSET" component="DOCMAN" priority="10" summary="Bug Generated By, UNCHECKED_ACCESS">Tool:UNCHECKED_ACCESS Date:2015-11-12
</jiraentry>

您可以在上一行看到打印的文本。下面是我使用转换器保存 xml 的 Java 代码。

         //normalize the xml file
         root.getDocumentElement().normalize();
         //remove standalone no
         root.setXmlStandalone(true);

         // write the content into xml file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         transformerFactory.setAttribute("indent-number", new Integer(0));//add intend to the new line

         Transformer transformer = transformerFactory.newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");

         DOMSource source = new DOMSource(root);
         StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(this.outpath), "UTF-8"));//save the file
         transformer.transform(source, result);

任何人都可以建议我让它更漂亮和清晰。

【问题讨论】:

  • 您的原始 xml 是否包含换行符?
  • 他们没有调用原始xml,程序通过转换根来创建xml。

标签: java xml


【解决方案1】:

你需要设置transformer的缩进量,如下面的sn-p所示:

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

有用参考:Similar Question

【讨论】:

  • 没有幸运还是一样
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多