Skip to Content

Groovy script mapping

May 14 at 05:32 AM


avatar image

HI Experts,

Can you please suggest me any blog/scenario for Creating groovy script mapping into a target hierarchal structure if you have already done that.


10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

2 Answers

Morten Wittrock
May 14 at 09:43 AM

Hi Vijender

It's not really complicated. There are two steps to it:

  1. Parsing the current message body
  2. Creating a new message body

Assuming the content is XML, step 1 is XML parsing and step 2 is building an XML document.

Parsing XML

To parse XML in Groovy, you have the groovy.util.XmlSlurper class available. In the following example, I'll be parsing this simple document:


Here's a short code snippet that parses the document and sums up the numbers:

import groovy.util.XmlSlurper

def lines = new XmlSlurper().parseText('<lines><line><num>10</num></line><line><num>20</num></line><line><num>30</num></line></lines>')

def sum = 0

lines.line.num.each { num -> sum += num.text() as Integer }

println sum

To parse the message body, you would instead run:

new XmlSlurper().parseText(message.getBody(java.lang.String))

You can read more about XML parsing in Groovy here.

Building an XML document

With Groovy's groovy.xml.MarkupBuilder class, building an XML document is really easy. Here's a piece of code that generates a simple document and replaces the message body with it:

import groovy.xml.MarkupBuilder

def Message processData(Message message) {
   def sw = new StringWriter()
   def builder = new MarkupBuilder(sw)
   builder.xmldoc {
      message("Hello, world!")
   return message

The code generates the following XML:

  <message>Hello, world!</message>

More MarkupBuilder examples can be found here.

So, what you need to do now, is combine the two techniques, and implement your specific requirements.

Have fun,


10 |10000 characters needed characters left characters exceeded
Vijender Gouda May 14 at 10:40 AM

HI Morten Wittrock,

Thanks a lot for your reply ! It will be really apprecited if you could help me in the which the groovy script can be used as one to one mapping from source to target for the strcuture

Show 1 Share
10 |10000 characters needed characters left characters exceeded

Hi Vijender

I'm afraid I don't quite follow. Using Groovy for mapping is about those two activities I described, and showed you code samples for.

Also, please note that you are replying to your own question right now, instead of commenting on my answer.