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.


Try it on Groovy IDE
import java.util.HashMap
import groovy.xml.*

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

Input Body


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>