保存xml时,为使其生成的文件格式规范化,可对TransformerFactory设置输出属性,如下。
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
/** * * @param folderPath * @param document */ private static void saveXML(String folderPath, Document document) { String filePath = folderPath + File.separator + "test.xml"; try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } }