Java Reference
In-Depth Information
er. The result is that you'll need to invoke a text method on each node to retrieve the text
data, but otherwise the two approaches are virtually the same.
Parsing XML is therefore quite easy. What about generating XML? That's the subject of
the next subsection.
B.8.2. Generating XML
So far, most of the Groovy capabilities presented are similar to what Java can do, just sim-
pler or easier. In this section I'll show a Groovy builder, which uses Groovy's metapro-
gramming to go beyond what Java can do.
To generate XML, Groovy provides a class called groovy.xml.MarkupBuilder .
You use a MarkupBuilder by invoking methods that don't exist, and the builder inter-
prets them by generating XML elements and attributes.
That sounds strange, but is simple in practice. The next listing shows an example.
Listing B.6. Generating XML using a MarkupBuilder
def builder = new groovy.xml.MarkupBuilder()
def department = builder.department {
deptName "Construction"
employee(id:1) {
empName "Fred"
}
employee(id:2) {
empName "Barney"
}
}
After instantiating the MarkupBuidler I invoke the department method on it, omit-
ting the optional parentheses. There's no department method on MarkupBuilder , so
what does Groovy do?
If this was Java, I would fail with something like a MissingMethodException . Every
class in Groovy has an associated meta class, however, and the meta class has a method
called methodMissing . The meta class is the key to Groovy's code generation cap-
abilities. When the methodMissing method in MarkupBuilder is called, the imple-
Search WWH ::




Custom Search