20060922

How to render a CDATA section inside an XML output using XSLT

When you are generating an output xml file from another xml using XSLT, usually need to output CDATA sections.

This is tricky and I always invented a new way to output it in each project.

Googling you can find some alternatives

I found this by myself


<jugador id="{@id}"><xsl:text disable-output-escaping="yes"><![CDATA[<![CDATA]]></xsl:text>[<xsl:value select="player"/><xsl:text>]</xsl:text><xsl:text disable-output-escaping="yes">]></xsl:text></jugador>


To obtain resulting XMLs like


<jugador id="51284393263"><![CDATA[Krankl]]></jugador>


I was shure that you can organize a contest of XSLT hacks to get this same result in a lot of simpler ways.

But the real solution, the KISS (Keep it simple stupid) solution is...

Put in your <xsl:output section cdata-section-elements="name of the element to be cdata escaped"

Example:


<xsl:output indent="yes" method="xml" cdata-section-elements="jugador"/>


Then if you have an xslt piece like:


<jugador id="{@id}"><xsl:value-of select="player"></xsl:value-of>


You will have the desired resulting XML, that is:


<jugador id="51284393263"><![CDATA[Krankl]]></jugador>


Automagically !


PD: Thanks to Michael Key for his great books:


Aqui en Michael Kay, quan encara estava conservat (XSLT 1.1)
friky foto



Michael Kay (alias Gandalf) molt més machacat (XSLT 2.0), aguantarà la versio 3.0 ???
friky foto

No hay comentarios: