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 }
  • 相关阅读:
    day 34
    day 33 线程锁
    day 32 操作系统、线程和进程(GIL锁)
    day 31 网络基础的补充
    day 30 多线程 socketserver模块补充
    python自学笔记 2019/07/01
    类与对象的概念
    递归及三种二分法
    好看的颜色
    zend 汉化
  • 原文地址:https://www.cnblogs.com/sherrykid/p/5336204.html
Copyright © 2011-2022 走看看