在Java中,如何在生成的XML文件中输出回车符,以使所有内容都不在一行上?
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("requests");
doc.appendChild(root);
root.appendChild(request);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
上面的代码创建了一个XML文件,但是全部都一行。
最佳答案
这应该可以解决此问题。
transformer.setOutputProperty(OutputKeys.INDENT, "yes");