SoapFaultException - 提取代码和文本

时间:2016-08-05 03:58:09

标签: java xml spring

我想从下面列出的soap fault中分别提取代码和文本。我正在使用的代码(在xml下面列出)是一起打印代码和文本。

<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 个答案:

答案 0 :(得分: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);