Groovy Examples

Go to list of examples

Merge Two XML Documents v2

Merge Two XML Documents v2

This script example is contributed by Raffael Herrmann.

You can compare the "Merge Two XML Documents" example with this one. This example is shorter and uses expressive features of Groovy.

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.

Script

Try it on Groovy IDE
import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import groovy.xml.*

def Message processData(Message message) {   
    //Parse sources
    def mainDoc = new XmlParser().parse(message.getBody(java.io.Reader))
    def extXml = message.getProperties().get("external_xml_data")
    def externalXmlDoc = new XmlParser().parseText(extXml)
    //Enhance and merge
    mainDoc.appendNode("Extension1").append(externalXmlDoc)    
    // Write document to body
    def result = (String)XmlUtil.serialize(mainDoc)    
    result = result.replaceAll("\n *?\n", "\n").trim()
    message.setBody(result)    
    return message
}

Input Body

<Root>
    <UsualElement>test</UsualElement>
    <AnotherField>123</AnotherField>
</Root>

Input Properties

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

Expected Result Body

<?xml version="1.0" encoding="UTF-8"?><Root>
  <UsualElement>test</UsualElement>
  <AnotherField>123</AnotherField>
  <Extension1>
    <ExternalData>
      <item>
        <key>key1</key>
        <value>value1</value>
      </item>
      <item>
        <key>key2</key>
        <value>value2</value>
      </item>
    </ExternalData>
  </Extension1>
</Root>