2016-08-05 53 views
0

我想從下面列出的soap故障中分別提取代碼和文本。我使用的代碼(下面列出的xml)是將代碼和文本一起打印出來。SoapFaultException - 提取代碼和文本

<env:Fault xmlns:env = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:fault = "http://schemas.xmlsoap.org/soap/envelope/"> 
    <faultcode>fault:Client</faultcode> 
    <faultstring>An error occurred. Please check the detail section.</faultstring> 
    <detail> 
     <e:serviceFault xmlns:e = "http://xml.comcast.com/types"> 
      <e:messages> 
       <e:message> 
        <e:code>ERRORCODE-82828</e:code> 
        <e:text>Error Message.</e:text> 
       </e:message> 
      </e:messages> 
     </e:serviceFault> 
    </detail> 
</env:Fault> 

代碼

public void printSoapFaultClientException(SoapFaultClientException e) { 
    TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
    Transformer transformer = null; 
    transformer = transformerFactory.newTransformer(); 

    DOMResult result = new DOMResult(); 

     transformer.transform(e.getSoapFault().getSource(), result); 
     NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail"); 

    System.out.println(" text content " + ((Element)nl.item(0)).getTextContent()); 

} 

回答

1

這裏是做它的一個例子,因爲它是一個故障XML,我剛使用一個解析器來解析XML和關閉提取字段它。另外SOAPFaultClientException API可以幫助您直接提取故障原因(http://docs.spring.io/spring-ws/site/apidocs/org/springframework/ws/soap/client/SoapFaultClientException.html

File fXmlFile = new File("C:\\DevelopmentTools\\3.CODE\\SOAP.txt"); 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse(fXmlFile); 
doc.getDocumentElement().normalize(); 

XPath xpath = XPathFactory.newInstance().newXPath(); 
String responseStatus = xpath.evaluate("//*[local-name()='code']/text()", doc); 
String responseText = xpath.evaluate("//*[local-name()='text']/text()", doc); 
System.out.println("---> " + responseStatus); 
System.out.println("---> " + responseText); 
+0

Thanks @Ramachandran。 Spring API只是返回faultCode和faultstring,不返回內部代碼和文本。 –

+0

xpath幫了很大忙。謝謝! –

+0

我在catch塊中捕獲(SoapFaultClientException e)。 我如何提取內部文本? –