Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MarkupBuilder Gotcha

DZone's Guide to

MarkupBuilder Gotcha

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

If you are not familiar with Groovy Builders they are certainly a beautiful creation. In fact you can generate an HTML page with something as simple as the following:

def writer = new FileWriter('blahsauce.html')
def src = new groovy.xml.MarkupBuilder(writer)

src.html {
head {
title 'My Awesome Sauce Page'
}
body {
p 'Hey this is a simple HTML paragraph created with a Groovy Builder!'
}
}

Just by looking at that you can probably tell what it is doing. It is creating a basic HTML page which sets a title for the page and then has one paragraph section. This example is very very basic, the Groovy MarkupBuilder can handle much more. One thing you should be aware of, hence the gotcha portion of this post's title, the MarkupBuilder does not support elements with intermingled text and child elements. So it can't be used to create the following HTML:

<p>Some element that has a <b> child element</b> which seems pretty basic.</p>

Every element has either a list of child elements or just text, but not both. The suggested work around, as of Groovy 1.5, is to use an HTML div tag.

Even though this little gotcha seems like a downer, don't fret Groovy Builders are still wonderfully useful and will continue to improve, so make sure you give them a chance.

Just for fun you should try the following and see what it generates:

def writer = new FileWriter('blahsauce.html')
def src = new groovy.xml.MarkupBuilder(writer)

src.html {
head {
title 'My Awesome Sauce Page'
}
body {
p 'Hey this is a simple HTML paragraph created with a Groovy Builder!' {
h1 'a test'
}
}
}

 

This post originated at my blog Stuff. Online.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}