CPI Groovy Examples

Go to List of Examples

Merge Two XML Documents

It is useful to have the extra data from another service in the same document and use it in a later mapping step.

For example, you might need external key-value data and map existing fields based on keys.

In this script, we create Extension1 element to make the resulting document more clear. You can add multiple extension elements to the same document.

The alternative is to apply this mapping in the same script without adding the extension element.


Try it on Groovy IDE
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import org.xml.sax.InputSource;

def Message processData(Message message) {

    def body = message.getBody(java.io.Reader)
    def mainDoc = new XmlParser().parse(body)

    def map = message.getProperties();
    String value = map.get("external_xml_data");
    def externalXmlDoc = new XmlParser().parse(new InputSource(new StringReader(value)))

    // Create "Extension1" element for clarity
    def nodeBuilder = new NodeBuilder();
    def node1 = nodeBuilder.Extension1{}

    // Merge

    // Write document to body
    def sw = new StringWriter()
    def xmlNodePrinter = new XmlNodePrinter(new PrintWriter(sw))
    xmlNodePrinter.with {
        preserveWhitespace = true

    String result = sw.toString()
    return message;

Input Body


Input Properties

external_xml_data<ExternalData> <item><key>key1</key><value>value1</value></item> <item><key>key2</key><value>value2</value></item> </ExternalData>

Expected Result Body