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

MarkupBuilder Gotcha

DZone's Guide to

MarkupBuilder Gotcha

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}