Skip to Content
Technical Articles

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

Hi,

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

<fields>

<body.secondary_contact>

<message>secondary_contact is required</message>

<value>

</value>

</body.secondary_contact>

<body.secondary_contact_number>

<message>secondary_contact_number is required</message>

<value>

</value>

</body.secondary_contact_number>

<body.workstream_prefix>

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

<value>

</value>

</body.workstream_prefix>

</fields>

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

 

Groovy script:

import com.sap.gateway.ip.core.customdev.util.Message;

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 { it.name() == ‘message’}.each { a ->allmessage << a.text()};
    int len = allmessage.size();
    while(i<allmessage.size())
    {
        errors=errors+”,”+allmessage[i];
        i++;
    }
        errors=errors.substring(1);
     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”);
     }
     message.setBody(errors);
    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,

Naveen

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