Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 150 ]

This technique is not limited to namespaces. We can use it anywhere that we need to
output a character in a tag name, which would otherwise not be valid as a Groovy
method name (for instance, hyphenated element names). Any Groovy string can
be used as an element name, so the following is also valid, where we use
${book_title} to paste the tag name into the markup from a local variable:


given:
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)

def book = "bk-book"
def book_title = "bk-title"

when:
xml."${book}" {
"${book_title}"("Cheaper by the Dozen")
"isbn_number"(1568491379)
}
then:
xmlIsIdentical writer.toString(), "book2.xml"

The MarkupBuilder class will slavishly emit whatever we ask it to. In the previous
code snippet, we are creating namespaces by using standard markup with the
MarkupBuilder class. A more elegant way of creating namespaced XML is by using
the StreamingMarkupBuilder class, which has built-in support for namespaces.


StreamingMarkupBuilder decouples the output of the markup from the creation of
the markup closure. We then bind the closure to StreamingMarkupBuilder at the
time at which we want the output to take place:


given:
def xml = new groovy.xml.StreamingMarkupBuilder()

when:
def markup = {
customers {
customer(id:1001) {
name(firstName:"Fred",surname:"Flintstone")
address(street:"1 Rock Road",city:"Bedrock")
}
customer(id:1002) {
name(firstName:"Barney",surname:"Rubble")
address(street:"2 Rock Road",city:"Bedrock")
}
}
}

then:
xmlIsIdentical xml.bind( markup ).toString(), "customers.xml"

http://www.ebook3000.com
Free download pdf