Skip to Content
Technical Articles

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,


1 Comment
You must be Logged on to comment or reply to a post.
  • Hi

    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.