码迷,mamicode.com
首页 > 其他好文 > 详细

格式化xml

时间:2016-06-20 21:53:00      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

在程序代码开发过程中,我们可能有时候需要将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     }

 

格式化xml

标签:

原文地址:http://www.cnblogs.com/yby-blogs/p/5601826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!