Chapter 7
[ 155 ]
}
}
tr {
td "groovy.util.FactoryBuilderSupport"
td {
table {
tr {
td "groovy.util.NodeBuilder"
}
tr {
td "groovy.swing.SwingBuilder"
} } } } } } }
then:
xmlIsIdentical writer.toString(), "table.html"
In the Groovy version, all of the tags that are produced are guaranteed to be
correct with respect to nesting and balancing. The Groovy version also looks much
less cluttered and readable. In fact, it is impossible for us to make the same type of
errors with the Groovy version, as the compiler will insist that all parentheses are
properly balanced.
Using program logic with builders
So far we have just used Groovy builders as straightforward markup code. In spite of
the unusual syntax, GroovyMarkup programs are still just plain Groovy code, so there
is nothing stopping us from mixing the construction process with regular program
logic if we please. Here we iterate over a list of customer data while generating XML
from the customer records that we find:
given:
def writer = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(writer)
def fred = new Customer(id:1001,firstName:"Fred",
surname:"Flintstone",
street:"1 Rock Road",city:"Bedrock")
def barney = new Customer(id:1002,firstName:"Barney",
surname:"Rubble",