Fork me on GitHub

格式化xml

在程序代码开发过程中,我们可能有时候需要将xml报文进行格式化一下,整理了一下,大概有两种方法:

 1 public String formatXml(String inputXml){
 2         SAXReader reader = new SAXReader();
 3         XMLWriter writer = null;
 4         String requestXml = null;
 5         try {
 6             Document document = reader.read(new StringReader(inputXml));
 7             if(document!=null){
 8                 StringWriter stringWriter = new StringWriter();
 9                 OutputFormat format = new OutputFormat(" ", true);
10                 format.setEncoding("GBK");
11                 format.setNewLineAfterDeclaration(false);//设置不存在空行
12                 writer = new XMLWriter(stringWriter, format);
13                 writer.write(document);
14                 writer.flush();
15                 requestXml = stringWriter.getBuffer().toString();
16             }
17         } catch (IOException e) {
18             e.printStackTrace();
19         } catch (DocumentException e) {
20             e.printStackTrace();
21         }finally{
22             if(writer!=null){
23                 try {
24                     writer.close();
25                 } catch (IOException e) {
26                     e.printStackTrace();
27                 }
28             }
29         }
30         return requestXml;
31     }
32     
33     public void formatXml2(String inputXml){
34         Format format = Format.getCompactFormat();
35         format.setEncoding("UTF-8");
36         format.setIndent(" ");
37         XMLOutputter outputter = new XMLOutputter(format);
38         org.jdom.Document document=null;
39         try {
40             ByteArrayOutputStream bo = new ByteArrayOutputStream(); 
41             StringReader reader = new StringReader(inputXml);
42             document = (new SAXBuilder()).build(reader);
43             outputter.output(document, bo);
44             System.out.println(bo.toString());
45         } catch (JDOMException e) {
46             e.printStackTrace();
47         } catch (IOException e) {
48             e.printStackTrace();
49         }
50     }

 

posted on 2016-06-20 20:58  骑着乌龟漫步  阅读(541)  评论(0编辑  收藏  举报

导航