Groovy Examples

Go to list of examples

Merge Two XML Documents

Merge Two XML Documents

Note: You can also check "Merge Two XML Documents v2" for a shorter & cleaner example.

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 org.xml.sax.InputSource;

def Message processData(Message message) {

    def body = message.getBody(
    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

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