views:

357

answers:

1

Hi all,

(sorry for the weird title...)

I want to use the groovy builder system to create a xml.

My problem is that i want to have some kind of envelop around, which the user dont has to care about.

An example:

def builder = new groovy.xml.MarkupBuilder()
builder.foo() {
     bar('hello')
}

this should create lets say

<Something id:'123'>
    <AnyInfo>
        <foo>
            <bar>hello</bar>
        </foo>
    </AnyInfo>
</Something>

so that there is a xml structure in the background in which the user can add his xml structure at a predefined node (in the example 'AnyInfo')

How does the builder has to look like, that I can add nodes with the markupbuilder (or any other builder) somewhere in the middle of the envelop ?

I hope this was somehow understandable ?!

THANKS Marty

+3  A: 

You can do this easily with closures. Create a closure to create the wrapper. You can then dynamically hand in your closure that creates the actual content. Example:

def writer = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(writer)

def createWrapper = {Closure c->
    builder.Something(id:123) {
        AnyInfo() {
            c()
        }
    }
}

createWrapper {
    builder.foo() {
        bar('hello')
    }
}

println writer.toString()

The result created by this is the sample XML you were looking for.

Chris Dail
great - easy and neat... thanks :)
Marty