dom4j 常用操作

1 读xml文件

 1     public static String read(String path) {
 2         
 3         String str = null;
 4         
 5         try {
 6             SAXReader reader = new SAXReader();
 7             Document document = reader.read(new File(path));
 8             str = document.asXML();
 9         } catch (Exception e) {
10             e.printStackTrace();
11         }
12         
13         return str;
14     }

 

2 格式化XML字符串

 1     /**
 2      *  格式化XML字符串
 3      */
 4     public static String formatXML(String str) {
 5         
 6         try {
 7             Document doc = DocumentHelper.parseText(str);
 8             
 9             OutputFormat format = OutputFormat.createPrettyPrint();
10             format.setEncoding("utf-8");
11             //format.setSuppressDeclaration(true);  // 抑制指令声明
12             format.setIndent(true);
13             format.setIndentSize(8);
14             
15             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
16             XMLWriter writer = new XMLWriter(outputStream, format);
17             
18             writer.write(doc);
19             writer.close();
20             
21             return outputStream.toString("utf-8").trim();
22             
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26         return str;
27     }

 

posted @ 2015-06-12 21:27  asnjudy  阅读(290)  评论(0编辑  收藏  举报