我尝试以漂亮的输出将文档保存到 XML 中。但问题是每个新元素都从前一个元素结束标记的行开始。
示例:
<?xml version="1.0" encoding="UTF-8"?><report>
<jiraentry category="SERVICE & ASSET" component="DOCMAN" priority="10" summary="Bug Generated By, UNCHECKED_ACCESS">Tool:UNCHECKED_ACCESS Date:2015-11-12
</jiraentry>
您可以看到它以及上一行中打印的文本。下面是我的 Java 代码,我用它来使用转换器保存 xml。
//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);
任何人都可以建议我让它变得更加漂亮和清晰。
最佳答案
您需要设置转换器的缩进量,如下面的代码片段所示:
t.setOutputProperty(OutputKeys.INDENT, "是");
t.setOutputProperty("{http://xml.apache.org/xslt}缩进量", "2");
有用引用:Similar Question
关于JAVA 8 xml 漂亮输出无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33497327/