简体   繁体   中英

Groovy MarkupBuilder node

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).

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM