Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 148 ]

Constructing this simple snippet of XML in Java requires numerous method calls to
create XML elements and to set the attributes of these elements. The nested structure
of the document would need to be explicitly constructed by appending some
elements as children of other elements. By the time that we are done coding, the
procedural nature of the construction process means that the code doing the markup
bears no resemblance to the end result XML.


MarkupBuilder

Consider the GroovyMarkup equivalent. In the following code, we use a Groovy
MarkupBuilder class to construct the same snippet of XML as in the previous
section. The xmlIsIdentical method uses XMLUnit to test whether both XML
snippets are the same:


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

def customers = builder.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 (writer.toString(), "customers.xml" )

The striking thing about the previous code snippet is that, unlike the Java code
required to do the same, this snippet is remarkably similar in structure to the XML
that is output. In this example, we are using the MarkupBuilder class from the
groovy.xml package. MarkupBuilder is one of several builder classes provided out
of the box as part of the Groovy JARs. MarkupBuilder can be used to effortlessly
build XML- and HTML-formatted output. What we are in fact looking at is a series of
nested closures, one within the other. The nesting of the closures exactly matches the
tree-like structure of the desired XML output.


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