Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 7

[ 149 ]

Namespaced XML


What if we would like to create namespaced XML? In GroovyMarkup, tags conform
to the method call syntax. So how can we do that if namespace:tag is not a valid
Groovy method name? Fortunately, there is a way around this. In order to insert
the colon into a tag name, we simply surround the element name in quotes. Groovy
allows us to invoke a method by using a string in place of the method name,
so "myMethod"() is treated the same as myMethod():


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

def params = [:]

when:
params."xmlns:bk" = "urn:loc.gov:books"
params."xmlns:isbn" = "urn:ISBN:0-393-36341-6"

def bk_tag = "bk:book"
xml."bk:book"(params) {
"bk:title"("Cheaper by the Dozen")
"isbn:number"(1568491379)
}

then:
xmlIsIdentical writer.toString(), "book1.xml"

Here we are using the strings' references to set the xmlns namespaces for bk and
isbn. Then we use strings to declare the element names in our markup. All of this
results in the following output:


<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>
Free download pdf