Java Reference
In-Depth Information
Once I have a MarkupBuilder I write out the song's properties as though I was building
the XML itself. Let's focus on the conversion of a single song to XML form, as shown
next:
MarkupBuilder builder = new MarkupBuilder(sw)
builder.song(id:s.id) {
title s.title
artist s.artist
year s.year
}
The job of the MarkupBuilder is illustrated in figure 4.8 .
Figure 4.8. Generating an XML representation of an object using a groovy.xml.MarkupBuilder
This is an example of Groovy's metaprogramming capabilities, though it doesn't look like
it at first. The idea is that inside the builder, whenever I write the name of a method that
doesn't exist, the builder interprets it as an instruction to create an XML element. For ex-
ample, I invoke the song method on the builder with the argument being a map with a key
called id and a value being the song's ID. The builder doesn't have a song method, of
course, so it interprets the method call as a command to build an element called song , and
the argument is an instruction to add an id attribute to the song element whose value is
the song ID. Then, when it encounters the curly brace it interprets that as an instruction to
begin child elements.
I have three more method calls: one to title , one to artist , and one to year . The
lack of parentheses can be misleading in this case, but each is actually a method call. Once
again the builder interprets each of the non-existent methods as commands to create XML
elements, and the arguments this time, because they're not in map form, become character
data contained in the elements. The result of the builder process is the XML shown next:
 
Search WWH ::




Custom Search