String类型的XML文件的格式化

在接收到的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值