String类型的XML文件的格式化

拟墨画扇 提交于 2020-03-21 11:10:13

在接收到的xml报文中,未经过格式化,不好看

 

 1 package org.zln.xml.format;
 2 
 3 import org.dom4j.Document;
 4 import org.dom4j.DocumentException;
 5 import org.dom4j.io.OutputFormat;
 6 import org.dom4j.io.SAXReader;
 7 import org.dom4j.io.XMLWriter;
 8 
 9 import java.io.*;
10 
11 /**
12  * Created by sherry on 16/3/29.
13  */
14 public class FormatXml {
15     public static void main(String[] args) {
16         String path = "";
17         String fileName = "";
18         formatXml(path,fileName);
19     }
20 
21     private static void formatXml(String path, String fileName) {
22         SAXReader saxReader = new SAXReader();
23         Document document;
24         BufferedReader bufferedReader = null;
25         try {
26             bufferedReader = new BufferedReader(new FileReader(new File(path,fileName)));
27             StringBuilder stringBuilder = new StringBuilder();
28             String line = null;
29             while ((line = bufferedReader.readLine())!=null){
30                 stringBuilder.append(line);
31             }
32             document = saxReader.read(new ByteArrayInputStream(stringBuilder.toString().getBytes("UTF-8")));
33             OutputFormat outputFormat = OutputFormat.createPrettyPrint();
34             XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File(path,"new_xml_"+fileName)),outputFormat);
35             xmlWriter.write(document);
36             xmlWriter.close();
37         } catch (FileNotFoundException e) {
38             e.printStackTrace();
39         } catch (IOException e) {
40             e.printStackTrace();
41         } catch (DocumentException e) {
42             e.printStackTrace();
43         }finally {
44             if (bufferedReader!=null){
45                 try {
46                     bufferedReader.close();
47                 } catch (IOException e) {
48                     e.printStackTrace();
49                 }
50             }
51         }
52     }
53 }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!