How to output CDATA with XSL

ExampleA CDATA element can be used to present formatted data or an XML document on its own.  The problem is that the XSLT processor will normally strip any leading and trailing whitespace, as well as carriage returns from an output XML document – unless instructed otherwise…

The correct use of the <xsl:output> element lets you define CDATA sections in the XML output.  The cdata-section-elements attribute allows you to define a space-separated list of XML element names: Each of these elements are output as CDATA sections in your target document – thus preserving the intended formatting.


Example

The following XSL transform shows how to preserve formatting in an XML document output. The comments node is set to output as a CDATA section. The content of this element / section can be built using a combination of text and / or XSL functions.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" cdata-section-elements="comments"/>
<xsl:template match="/">
<comments>This is a formatted text section.
Normally XML / XSLT parsers strips whitespace/carriage returns.

A
B
C

See - told you so.
</comments>
</xsl:template>
</xsl:stylesheet>

The XSL transform generates the following output. The formatted text is wrapped in a CDATA section.

<?xml version="1.0" encoding="UTF-8"?>
<comments>
<![CDATA[This is a formatted text section.
Normally XML / XSLT parsers strips whitespace/carriage returns.

A
B
C

See - told you so.
]]>
</comments>

Posted in XSLT and tagged .

Leave a Reply