Monday, September 17, 2007

Groovy XML Markup Builder CDATA block

This is one of those things that turns out to be easy but takes a bit of time to figure out.

Using Groovy's builders there are times where you want more control, like when you want to pump out a CDATA block. This turns out to be quite straight forward:

out = new StringWriter()
xml = new groovy.xml.MarkupBuilder(out);
xml.test_xml {
normal("Some text in a normal element")
data('') {
out.write("<![CDATA[Hello]]>")
}
}
println out

Basically since we have reference to the writer we can dump out anything directly to it. I'm sure this works with most builders.

The resulting xml block should look like:

<test_xml>
<normal>Some text in a normal element</normal>
<data><![CDATA[Hello]]></data>
</test_xml>


UPDATE EDIT:

Please note that MarkupBuilder also gives you the special field 'mkp' to do similar actions.

For example:

def out = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(out)

xml.test_xml {
normal("Some text in a normal element")
xml.mkp.yieldUnescaped('<data><![CDATA[Hello]]></data>')
}

println out


Also works and probably is more-correct.