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:If you prefer to define a default namespace instead do this: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()
xml.person(xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}
Finally, here is an example that uses them all:This will output:xml.'person:person'('xmlns:person': 'http://people.org', xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}
<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?