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

MarkupBuilder Gotcha

DZone's Guide to

MarkupBuilder Gotcha

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}