Skip to main content

Scenario

If you want to make changes only when there is an error condition in an XML message containing error, XmlSlurper Groovy can be used.

Sample Message

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <soap:Fault>
            <faultcode>
                soap:Server
            </faultcode>
            <faultstring>
                javax.xml.ws.WebServiceException: com.exception.BaseUserException: Some Error.
            </faultstring>
        </soap:Fault>
    </soap:Body>
</soap:Envelope>

Groovy Script

import groovy.xml.XmlSlurper
import groovy.xml.XmlUtil

var rootNode = new XmlSlurper(false, true).parseText(responseBodyTextFromTargetAPI).declareNamespace('soap':'http://schemas.xmlsoap.org/soap/envelope/')

def element=rootNode.'soap:Body'.'soap:Fault'.'faultstring'

if(element != ''){
  rootNode.'soap:Body'.'soap:Fault'.replaceNode { }
  rootNode.'soap:Body'.appendNode {
    faultstring(element.text())
  }
  responseBodyTextFromTargetAPI = XmlUtil.serialize(rootNode)
}

Result

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <faultstring>
            javax.xml.ws.WebServiceException: com.exception.BaseUserException: Some Error.
        </faultstring>
    </soap:Body>
</soap:Envelope>