cancel
Showing results for 
Search instead for 
Did you mean: 

Need help on groovy script to sum the XML and aggregate

former_member113404
Discoverer
0 Kudos

Hi Folks,

Please help me on below requiremtn using groovy script

I want to do the mapping suing groovy script to sum and aggregate the output

my source is:

<root>
<row>

<userId>0002</userId>
<PayrollID>1</PayrollID>
<Marks>100</Marks>
</row>
<row>

<userId>0001</userId>
<PayrollID>1</PayrollID>
<Marks>200</Marks>
</row>
<row>

<userId>0002</userId>
<PayrollID>1</PayrollID>
<Marks>300</Marks>
</row>
<row>

<userId>0001</userId>
<PayrollID>1</PayrollID>
<Marks>300</Marks>
</row>
</root>
------------------

My require out put is

---------
<root>
<row>

<userId>0002</userId>
<PayrollID>1</PayrollID>
<Marks>400</Marks>
</row>
<row>

<userId>0001</userId>
<PayrollID>1</PayrollID>
<Marks>500</Marks>
</row>

</root>

Regards

DV

MortenWittrock
Active Contributor
0 Kudos

Hi DV

What have you tried so far? If you post your script, we have a better chance of helping you out.

Regards,

Morten

MortenWittrock
Active Contributor
0 Kudos

Also, why are you solving this in Groovy, specifically?

Morten

Accepted Solutions (0)

Answers (3)

Answers (3)

0 Kudos

The sum value is coming as 0 for me. Did this code work?

gagandeep_batra
Active Contributor
0 Kudos

Hello DV,

You can try with following code, that might help you :

--------------

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.xml.MarkupBuilder

def Message processData(Message message) {

String body = message.getBody(java.lang.String) as String;

// Build XML Document
//SAXBuilder builder = new SAXBuilder();
def worklogs = new XmlSlurper().parseText(body);
def stringWriter = new StringWriter()
def peopleBuilder = new MarkupBuilder(stringWriter)
def t11=0;


//def with_kids=node.findAll {it.userId.unique()}
def btNumbers = worklogs.row.collect{it.userId}
def countMap = btNumbers.unique(false).collectEntries{btNumber->
[btNumber, btNumbers.count(btNumber)]
}
peopleBuilder."root"{

countMap.each {k,v ->
worklogs.row.each {node ->
if(k == node.userId.text())
{
le=node.Marks.text()
t11=t11+ le.toInteger()
}
}
rowout{
key(k)
Value(v)
total(t11)
}
t11=0

}

}





def xml1 = stringWriter.toString()
message.setBody(xml1);



return message;
}

---------------------

Regards

GB

MortenWittrock
Active Contributor
0 Kudos

Hello again

If you want to solve this in Groovy, you will need to first parse the message body XML, sum up the contents of the <Marks> elements, and then output a new XML document containing the aggregated sums. I've just answered another question, that describes in some more detail how to do this.

Regards,

Morten