在接收到的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 }
来源:https://www.cnblogs.com/sherrykid/p/5336204.html