保存xml時,爲使其生成的文件格式規範化,可對TransformerFactory設置輸出屬性,以下。apache
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(); } }