Friday, February 10, 2017

Groovys MarkupBuilder and Namespaces

Groovys 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 Groovys 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(>
<name>Jim</name>
<phone>555-1234</phone>
<person:person>
I think its 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?

Available link for download