随题而学(四)xml文件格式规范化

 

保存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();
        }
    }

 

posted on 2015-04-08 17:07  云中园  阅读(353)  评论(0编辑  收藏  举报

导航