XSLT and verbatim content with CDATA sections

Here’s a quick tip you may find useful while writing some – maybe complex – XSLT transformations.

I adopted this solution recently for some library code that emits RSS complaint XML documents.

My need was to create XML fragments that contain unescaped HTML content, so that I could easily create HTML formatted elements values without worrying too much about HTML encoding.

Of course, CDATA sections were a suitable (and easy) option.

But you cannot include CDATA sections as such in the processing transformation, since it would have caused an automatic escaping of the inner content…. unless… you specify that one or more of the output elements will indeed contain CDATA sections.

You can achieve this goal just by specifying a cdata-section-elements as an attribute of the XSL element output (see this excerpt from the XSL reference documentation):

<output>
method = xml | html | text | qname-but-not-ncname
version = nmtoken
encoding = string
omit-xml-declaration = yes | no
standalone = yes | no
doctype-public = string
doctype-system = string
cdata-section-elements = qnames
indent = yes | no
media-type = string
Model: EMPTY
</output>

Credits go to Bernie Zimmermann, whose detailed post you can find here: http://www.bernzilla.com/2008/02/12/utilizing-cdata-section-elements-in-xsl/