zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    金额相关的测试用例
    Python练习题--持续更新
    Python基础--函数
    Python基础--文件操作和集合
    Python基础--数据类型
    Python基础--字典
    分布式理论(七)—— 一致性协议之 ZAB
    分布式理论(六)—— Raft 算法
    分布式理论(五)—— 一致性算法 Paxos
    分布式理论(四)—— 一致性协议之 3PC
  • 原文地址:https://www.cnblogs.com/sherrykid/p/5336204.html
Copyright © 2011-2022 走看看