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?
3 comments:
You know deep down inside that Ruby is the language you desire James. ;)
...And while I'm thinking about programming language wars, I must link to this:
http://davidrupp.blogspot.com/2007/10/last-language-war-language-trolling.html
Good stuff James.
I actually like your solution.
For as much as I'm diggin' on Ruby these days - it definitely falls flat is a few areas. XML processing is one of those.
If I had a reason to - I'd like to do some work with Groovy.
very informative blog and useful article thank you for sharing with us, keep posting Ruby on Rails Online Course India
Post a Comment