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.

Script

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
    node1.append(externalXmlDoc)
    mainDoc.append(node1)

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

    String result = sw.toString()
    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

<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>