cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How do I read child XML nodes with multiple occurrence as a string using groovy script

advitramesh
Explorer
0 Kudos
1,712

Hello Experts

I am looking at reading the xml nodes with multiple occurrence and copying it as a string along with the xml tags. In the below example I am looking at copying the attachments xml tags as a string

Input

<?xml version="1.0" encoding="utf-8"?>

<newHire>

<applicationID>20025</applicationID>

<startDate>2022-02-15T09:00:00</startDate>

<userName>test@gmail.com</userName>

<email>test@gmail.com</email>

<employmentType>1789</employmentType>

<position>41000332</position>

<payGrade>S17</payGrade>

<company>6910</company>

<contractType>1651</contractType>

<firstName>Micheal</firstName>

<lastName>Essien</lastName>

<preferredName>Micheal</preferredName>

<employeeClass>1781</employeeClass>

<attachments>

<name>DriversLicence</name>

<fileName>DriversLicence.jpg</fileName>

<fileContent>Base64Format</fileContent>

<documentType>DL</documentType>

<notes>DriversLicence</notes>

</attachments>

<attachments>

<name>Passport</name>

<fileName>Passport.jpg</fileName>

<fileContent>Base64Format</fileContent>

<documentType>Passport</documentType>

<notes>Passport</notes>

</attachments>

</newHire>

Output

<attachments><name>DriversLicence</name><fileName>DriversLicence.jpg</fileName><fileContent>Base64Format</fileContent><documentType>DL</documentType><notes>DriversLicence</notes></attachments><attachments><name>Passport</name><fileName>Passport.jpg</fileName><fileContent>Base64Format</fileContent><documentType>Passport</documentType><notes>Passport</notes></attachments>

I am new to groovy and I was exploring XmlSlurper and I have noticed GpathResult will fetch the value but not the xml tags

Can you please let me know how I can meet this requirement.

Appreciate your support

Regards

Advit

View Entire Topic
Joe_Girard
Discoverer

Hey,

You can do that with Groovy pretty easy.

Here is a simple script that does exactly that. You can take the methodology and adapt as needed.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap


def Message processData(Message message) {
    Reader reader = message.getBody(Reader)
    def root = new XmlSlurper().parse(reader)
    
    StringBuffer text = new StringBuffer()

    root.attachments.each{ attachment ->      
        text.append("<attachments>")
        attachment.'*'.each{
            def tag = it.name()
            def value = it.text()
            text.append("<$tag>$value</$tag>")
        }
        text.append("</attachments>")
    }

    message.setBody(text.toString())
    return message
}