dom4j格式化xml文件

dom4j格式xml并输出为*.xml文件 
Java代码  
  1. public static void main(String[] args) {     
  2.     Document document = DocumentHelper.createDocument();        
  3.     Element employees=document.addElement("employees");        
  4.     Element employee=employees.addElement("employee");        
  5.     Element name= employee.addElement("name");        
  6.     name.setText("jim");        
  7.     Element sex=employee.addElement("sex");        
  8.     sex.setText("male");        
  9.     Element age=employee.addElement("age");        
  10.     age.setText("29");        
  11.     try {        
  12.         OutputFormat format = new OutputFormat();     
  13.         format.setIndent(true);     
  14.         format.setNewlines(true);     
  15.         Writer fileWriter=new FileWriter("F:/test.xml");        
  16.         XMLWriter xmlWriter=new XMLWriter(fileWriter,format);        
  17.         xmlWriter.write(document);        
  18.         xmlWriter.close();                           
  19.     } catch (IOException e) {        
  20.         System.out.println(e.getMessage());        
  21.     }               
  22. }  

dom4j格式化xml并格式化输出 
Java代码  
  1. public static String formatXml(String str) throws DocumentException, IOException {  
  2.     SAXReader reader=new SAXReader();  
  3.     StringReader in=new StringReader(str);  
  4.     Document doc=reader.read(in);  
  5.     OutputFormat formater=OutputFormat.createPrettyPrint();  
  6.     formater.setEncoding("UTF-8");  
  7.     StringWriter out=new StringWriter();  
  8.     XMLWriter writer=new XMLWriter(out,formater);  
  9.     writer.write(doc);  
  10.     writer.close();  
  11.     return out.toString();  
  12. }  

你可能感兴趣的:(dom4j格式化xml文件)