cancel
Showing results for 
Search instead for 
Did you mean: 

Finding xml value based on attribute value in groovy script

Robert_d_Hoedt
Explorer
0 Kudos

Hi,

I have this payload

<?xml version="1.0" encoding="utf-8"?>
<ReferenceInformation>
<AssignmentId>
<IdValue name="customid">JOB182741</IdValue>
<IdValue name="reference">1234XYZ</IdValue>
</AssignmentId>
</ReferenceInformation>
 
I want to find the IdValue where attribute name = "customid" and store that value in an exchange property
I created a groovyscript based on code snippets i found when searching but sofar i did not manage to make it work.
 
This is my groovyscript:
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message) {
       def xml = message.getBody(String.class)      
       def completeXml = new XmlSlurper().parseText(xml)
       def netive_jobid = completeXml.ReferenceInformation.AssignmentId.IdValue[@name="customid"].text()
       message.setProperty("NTV_JOBID", netive_jobid)
       return message
}
But i get 2 errors
1)   unexpected token: = @ line 7, column 86.
2)   TypeError: Cannot convert undefined or null to object
 
I am not sure where i am going wrong. 
Any help is appreciated
 
Kr
Robert
 

Accepted Solutions (1)

Accepted Solutions (1)

Robert_d_Hoedt
Explorer
0 Kudos

I found the answer using chatgpt.

On the message:

   <HumanResource>
      <AssignmentId>
         <IdValue name="recordid">a0j6N000002HDkmQAG</IdValue>
         <IdValue name="externalid">8324137</IdValue>
         <IdValue name="customid">JOB182741</IdValue>
      </AssignmentId>
   </HumanResource>
 
The script:
import groovy.util.XmlSlurper
import com.sap.gateway.ip.core.customdev.util.Message

def Message processData(Message message) {
    def xml = message.getBody(String.class)
    def completeXml = new XmlSlurper().parseText(xml)
    def NTV_JOBID = completeXml.AssignmentId.IdValue.find { it.@name == 'customid' }.text()          
   
    message.setProperty("NTV_JOBID", NTV_JOBID)
    return message
}
 
Produces the exhange property NTV_JOBID with value JOB182741
 
Few things that i noticed
1) originally i did not do import of groovy.util.XmlSlurper
2) in walking down the tree you must NOT start at the root (HumanResource), but 1 down (AssignmentId)
3) the part between {} is quite different than i thought it would be. My guess was more like an x-path query as it would look when you set an exchange property directly in CPI. I'm still not sure what it. stands for, but it works.
 
Bit of a frustrating search but finding it in the end still makes me happy.
 
Kr
Robert
 

Answers (0)