Showing posts with label markupbuilder. Show all posts
Showing posts with label markupbuilder. Show all posts

Thursday, February 28, 2008

Groovy's MarkupBuilder and Namespaces

Yesterday Kit Plummer posted an XML example using Ruby to demonstrate how to include attributes and namespaces. So I went on a quest to duplicate his output using Groovy to compare the difference and evangelize.

Here is the desired output:

<person:person text='test'>
<name>Jim</name>
<phone>555-1234</phone>
</person:person>
Using the Groovy Console, and Groovy's ninja-like MarkupBuilder, you can execute the following script to get attributes and namespace prefixes:
import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.'person:person'(text: 'test') {
name('Jim')
phone('555-1234')
}

println writer.toString()

If you prefer to define a default namespace instead do this:
xml.person(xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}
Finally, here is an example that uses them all:
xml.'person:person'('xmlns:person': 'http://people.org', xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}

This will output:
<person:person xmlns:person='http://people.org' xmlns='http://people.org' text='test'>
<name>Jim</name>
<phone>555-1234</phone>
<person:person>
I think it's more readable than the Ruby example and definitely much better than the equivalent Java code.

By the way, I attempted to use this online syntax highlighter and did not like it. Does anyone know of a good online syntax highlighter?