格式化XML

dom4j写XML文件,如不格式化,就只会把全部内容全写在一行上,看起来很难看。要实现分层次的格式化,可使用如下的方法:

public static void formatXMLFile(Document document,String filename){
	       try{
	           XMLWriter writer = null;
	           /** 格式化输出,类型IE浏览一样 */
	           OutputFormat format = OutputFormat.createPrettyPrint();
	           /** 指定XML编码 */
	           format.setEncoding("GBK");
	           writer= new XMLWriter(new FileWriter(new File(filename)),format);
	           writer.write(document);
	           writer.close();      
	       }catch(Exception ex){
	           ex.printStackTrace();
	       }
	    }

猜你喜欢

转载自lianghao619.iteye.com/blog/1355290