---
title: "XML Format  xml格式化  xml pretty print"
author: "butterflymacro"
date: "2012-08-28T17:54:44Z"
tags: []
categories: ["编程语言"]
slug: "xml-format-xml-xml-pretty-print"
draft: false
lastmod: "2012-08-28T17:54:44Z"
id: 1665570
url: "https://butterflymacro.iteye.com/blog/1665570"
---

XML pretty print,  XML format,  XML 格式化

今天在项目中用到WebService,发现有时候可能SOAP消息，可能是服务端返回或者客户端请求都有可能 不是格式化好的SOAP消息

例如

&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;soap:Body&gt;&lt;ns2:do\_modifyUserBasicInfo xmlns:ns2="http://imsintf.service.openbilling.ailk.com/"&gt;&lt;sOper&gt;&lt;so\_nbr&gt;10262&lt;/so\_nbr&gt;&lt;busi\_code&gt;1033&lt;/busi\_code&gt;&lt;so\_mode&gt;2&lt;/so\_mode&gt;&lt;so\_date&gt;2012-08-28 01:20:34&lt;/so\_date&gt;&lt;charge\_flag&gt;1&lt;/charge\_flag&gt;&lt;source\_system&gt;01&lt;/source\_system&gt;&lt;/sOper&gt;&lt;sUser&gt;&lt;phone\_id&gt;0852273049&lt;/phone\_id&gt;&lt;password&gt;123456&lt;/password&gt;&lt;/sUser&gt;&lt;/ns2:do\_modifyUserBasicInfo&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;

整个报文就一行,让人很难看到参数的具体值

项目中要求输出合格化的XML报文(Indent) 或者说是pretty print   xml树形结构.

如：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;

&lt;soap:Body&gt;

&lt;ns2:do\_modifyUserBasicInfo xmlns:ns2="http://imsintf.service.openbilling.ailk.com/"&gt;

&lt;sOper&gt;

&lt;so\_nbr&gt;10400&lt;/so\_nbr&gt;

&lt;busi\_code&gt;1033&lt;/busi\_code&gt;

&lt;so\_mode&gt;2&lt;/so\_mode&gt;

&lt;so\_date&gt;2012-08-28 05:35:28&lt;/so\_date&gt;

&lt;charge\_flag&gt;1&lt;/charge\_flag&gt;

&lt;source\_system&gt;01&lt;/source\_system&gt;

&lt;/sOper&gt;

&lt;sUser&gt;

&lt;phone\_id&gt;0852273049&lt;/phone\_id&gt;

&lt;password&gt;123456&lt;/password&gt;

&lt;/sUser&gt;

&lt;/ns2:do\_modifyUserBasicInfo&gt;

&lt;/soap:Body&gt;

&lt;/soap:Envelope&gt;

 

项目中使用的Spring集成CXF,查阅CXF可以使用拦截器来实现报文的输出,在通过 XML 的TransformerFactory  Transformer 来实现XML的格式化

代码如下

public class SOAPMessageInterceptor implements SOAPHandler&lt;SOAPMessageContext&gt;{

 

private Logger log = LoggerFactory.getLogger(SOAPMessageInterceptor.class);

public boolean handleMessage(SOAPMessageContext context) {

// TODO Auto-generated method stub

ByteArrayOutputStream bos = new ByteArrayOutputStream();

SOAPMessage message = context.getMessage();

StringBuilder sb = new StringBuilder();

boolean isOutBound =(Boolean)context.get(MessageContext.MESSAGE\_OUTBOUND\_PROPERTY);

sb.append("\*\*\*invoke WebService\*\*\**   EndPoint Method "+getMethodName(context) + "\\n");

if(isOutBound){

sb.append("\\nInbound Message:\\n");

}else{

sb.append("\\nOutbound  Message:\\n");

}

 

try {

message.writeTo(bos);

Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

Source xmlInput = new StreamSource(bis);

bos.reset();

StreamResult xmlOutput = new StreamResult(bos);

transformer.transform(xmlInput,xmlOutput);

sb.append(bos.toString());

sb.append("\\n\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\\n");

 

}catch(Exception e){

e.printStackTrace();

}

log.info(sb.toString());

return true;

}

 

 

 protected String getMethodName(MessageContext mc)

     {

         String operationName = null;

         try

         {

            SOAPMessageContext messageContext = (SOAPMessageContext) mc;

 

            // assume the operation name is the first element

            // after SOAP:Body element

            Iterator i = messageContext.getMessage().getSOAPPart().getEnvelope().getBody().getChildElements();

            while ( i.hasNext() )

            {

                Object obj = i.next();

                if(obj instanceof SOAPElement)

                {

                    SOAPElement e = (SOAPElement) obj;

                    operationName = e.getElementName().getLocalName();

                    break;

                }

            }

         }

         catch(Exception e)

         {

             e.printStackTrace();

         }

         return operationName;

     }

public boolean handleFault(SOAPMessageContext messagecontext) {

// TODO Auto-generated method stub

return true;

}

public void close(MessageContext messagecontext) {

// TODO Auto-generated method stub

}

public Set&lt;QName&gt; getHeaders() {

// TODO Auto-generated method stub

return null;

}

}