Groovy web console

subscribe to the feed Subscribe
to this
site

Mapping for CPI

Published 2 months ago by Ivan Garcia
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def xml = '''<?xml version='1.0' encoding='UTF-8'?><root>
<Objects>
<Int_ContractAgreement__c>a0q1l000004cIgOAAU</Int_ContractAgreement__c>
<Int_Outlet__c>0010252738</Int_Outlet__c>
<GroupCode__c>4397</GroupCode__c>
<BottleSize__c>118</BottleSize__c>
</Objects>
<Objects>
<Int_ContractAgreement__c>a0q1l000004cIgOAAU</Int_ContractAgreement__c>
<Int_Outlet__c>0010252738</Int_Outlet__c>
<GroupCode__c>4603</GroupCode__c>
<BottleSize__c>318</BottleSize__c>
</Objects>
<Objects>
<Int_ContractAgreement__c>abcx</Int_ContractAgreement__c>
<Int_Outlet__c>0010234567</Int_Outlet__c>
<GroupCode__c>4397</GroupCode__c>
<BottleSize__c>118</BottleSize__c>
</Objects>
<Objects>
<Int_ContractAgreement__c>abcx</Int_ContractAgreement__c>
<Int_Outlet__c>0010234567</Int_Outlet__c>
<GroupCode__c>4403</GroupCode__c>
<BottleSize__c>118</BottleSize__c>
</Objects>

</root>'''

def parsedXml = new XmlSlurper().parseText(xml)

def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def transformedXml = builder.bind {
    mkp.xmlDeclaration() 
    root {    
            def objects= parsedXml.'**'.findAll{ it.name() == 'Objects'} 
            def objectsByContract = objects.groupBy({ object -> (object.Int_ContractAgreement__c.text()) })

            objectsByContract.each { mp -> 
                    Objects {
                       Int_ContractAgreement__c (mp.key)
                       Int_Outlet__c(mp.value[0].Int_Outlet__c.text())
                       mp.value.each { obj ->          
                         Int_Vol_Send {
                         GroupCode__c(obj.GroupCode__c.text())                
                         BottleSize__c(obj.BottleSize__c.text())
                         }
                       }
                    }  

               }

          }
    }

println groovy.xml.XmlUtil.serialize(transformedXml)