Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 7

[ 151 ]

Within the closure, we can reference a variable, mkp, which allows us to give
instructions to the builder in order to control XML generation. Two handy methods
we can invoke are xmlDeclaration(), which causes the XML declaration header to
be output, and declareNamespace(), which sets up a namespace:


given:
def xml = new groovy.xml.StreamingMarkupBuilder().bind {
mkp.xmlDeclaration()
mkp.declareNamespace('bk':'urn:loc.gov:books')
mkp.declareNamespace('isbn':'urn:ISBN:0-393-36341-6')

bk.book {
bk.title("Cheaper by the Dozen")
isbn.number(1568491379)
}
}

expect:
xmlIsIdentical xml.toString(), "book1.xml"

Once we have made the builder aware of our namespaces, we can utilize them in the
markup code by using suffix notation. So namespace.tag will be output in the XML
as namespace:tag, as follows:


<?xml version='1.0'?>
<bk:book xmlns:bk='urn:loc.gov:books' xmlns:isbn='urn:ISBN:0-393-
36341-6'>
<bk:title>Cheaper by the Dozen</bk:title>
<isbn:number>1568491379</isbn:number>
</bk:book>

The GroovyMarkup syntax

GroovyMarkup is nothing more than method call syntax combined with closures and
named parameters. But, in effect, these Groovy syntactical features are combined to
produce a new DSL syntax for GroovyMarkup with its own rules. Let's look in detail
at the syntax from the previous examples:


def customers = builder.customers {
...
Free download pdf