Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy MarkupBuilder node

Tags:

xml

groovy

Consider the following code:

def builder = new MarkupBuilder()
builder.root() {
}

I would like to delegate creation of the children of root to a separate method. How can I accomplish this task? Some options to consider are creating and returning a node from a method or passing in the parent node and adding them in the method (both examples would be useful).

like image 346
dromodel Avatar asked Apr 11 '26 13:04

dromodel


1 Answers

The Groovy website contains an explanation on how to achieve this.

Sample:

def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
xml.books() {
   createBookNode(xml, 2, 'mrhaki')
}

def createBookNode(builder, repeat, username) {
    repeat.times {
       builder.person(name: username)
    }
}

println writer.toString()

Output will be:

<books>
    <person name="mrhaki"/>
    <person name="mrhaki"/>
</books>
like image 102
mrhaki Avatar answered Apr 13 '26 04:04

mrhaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!