Skip to Content
-2

Need help on groovy script to sum the XML and aggregate

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

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

2 Answers

  • May 14 at 09:48 AM

    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

    Add comment
    10|10000 characters needed characters exceeded

  • May 14 at 10:23 AM

    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

    Add comment
    10|10000 characters needed characters exceeded