JAVA 8 xml漂亮的输出不能正常工作

时间:2015-11-03 10:55:09

标签: java xml

我尝试将文档保存到漂亮的输出中的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);

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

1 个答案:

答案 0 :(得分:0)

您需要设置变压器的缩进金额,如下面的代码段所示:

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

有用的参考:Similar Question