How to dynamically inject child nodes in Groovy MarkupBuilder?

579 views Asked by At

I'm trying to use Groovy MarkupBuilder to dynamically create my custom XML structure like below.

<envelope>
  <header>
    <key1>value1</key1>
  </header>
  <body>
    <payload />
  </body>
</envelope>

Though I got it working with the below code, I would like inject the 'payload' part of the code dynamically in a separate class where the 'builder' is passed in as a method parameter.

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

builder.envelope{
    header{
        key1("value1")
    }
    body{
        payload(){    
        }
    }
}

println writer.toString()

1

There are 1 answers

0
Opal On BEST ANSWER

Is that what You're looking for?

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

builder.envelope {
    header{
        key1("value1")
    }
    body {
       method(builder) 
    }
}

println writer.toString()

def method(b) {
    b.payload2()
}