Skip to Content
Technical Articles
Author's profile photo naveen kumar171

Groovy script to extract the repeated/particular XML node where the XML has dynamic parent node – SAP CPI


I tried to extract the repeated occurrence of an XML child node from the input, so I blogged and couldn’t found the one which suits my requirement. Hence I am writing this blog to make the use/modify of the script based on the requirement of yours.

My requirement:

Below is the input structure, where I need to extract and concatenate the message node from each dynamic parent node.

Input XML structure



<message>secondary_contact is required</message>





<message>secondary_contact_number is required</message>





<message>workstream_prefix must be a number string</message>





Ouput – secondary_contact is required,secondary_contact_number is required,workstream_prefix must be a number string


Groovy script:


import java.util.HashMap;
import java.util.*;
def Message processData(Message message)
    def body = message.getBody(java.lang.String) as String;
    def root = new XmlParser().parseText(body);
    def i=0;
    def errors=””;
    def allmessage=[];
        root.’**’.findAll { == ‘message’}.each { a ->allmessage << a.text()};
    int len = allmessage.size();
     def messageLog = messageLogFactory.getMessageLog(message);
       if(messageLog != null){
        messageLog.setStringProperty(“Logging#1”, “Printing Payload As Attachment”)
        messageLog.addAttachmentAsString(“only_message:”, len + “message – “+errors, “text/plain”);
    return message;



Using the above script, I fulfilled my requirements. Hope I will get some suggestions to achieve this in another way.

Appreciating the responses.

Thank you,


Assigned tags

      You must be Logged on to comment or reply to a post.
      Author's profile photo Daniel Graversen
      Daniel Graversen


      There is always multiply options to solve a goal.

      You could probably also perform this with XSLT, if you just wanted to extract the payloads. Thought it cannot place it into a MPL payload.

      I assume you can also append to the Error in the each loop, so you dont need to concatenate the strings after.


      Author's profile photo Sahaj Shetty
      Sahaj Shetty

      Can you recommend a script that can be used in the message mapping of CPI to concatenate recurring fields from an error response like the one below if I want to concatenate the messages tags.


      <?xml version="1.0" encoding="utf-8"?>
      <message xml:lang="en">An exception was raised.</message>
      <SAP_Note>See SAP Note 1797736 for error analysis (</SAP_Note>
      <message>Material Number received on invoice payload from XXXXX does not match</message>
      <message>with material on SAP PO 450000XXXXX item 00010</message>
      <message>An exception was raised</message>