MarkupBuilder Gotcha
Join the DZone community and get the full member experience.
Join For FreeIf 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.
Opinions expressed by DZone contributors are their own.
Trending
-
AI Technology Is Drastically Disrupting the Background Screening Industry
-
8 Data Anonymization Techniques to Safeguard User PII Data
-
IntelliJ IDEA Switches to JetBrains YouTrack
-
WireMock: The Ridiculously Easy Way (For Spring Microservices)
Comments