How to keep/add CDATA section with XSLT on specified subnodes?

Viewed 66

I have an XML File with the following structure:

<catalog>
    <category>
        <display-name>    XYZ       </display-name> 
    </category>
    <product>
        <display-name>    ABC       </display-name>
    </product>
</catalog>

How can I add CDATA section on all subnodes catalog/product/display-name ?

This is the kind of code I wrote , how can I chosse the specified subnodes on cdata-section-elements :

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="no" indent="yes" cdata-section-elements="?"/>
 <xsl:strip-space elements="*"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="catalog">
  <catalog catalog-id="master-catalog">
   <xsl:apply-templates select="@*|node()"/>
  </catalog>
 </xsl:template>
</xsl:stylesheet>

Thanks for help !

1 Answers

As I said in a comment, the standard way since XSLT 1 is to list cdata-section-elements="display-name", although that will apply to any display-name elements in the result.

In XSLT 3, if you want to serialize an element as a CDATA section based on its match pattern, you could use the serialize function on it and then the disable-output-escaping hack:

  <xsl:template match="category/display-name | product/display-name">
      <xsl:value-of select="serialize(., map { 'cdata-section-elements' : node-name() })"
                    disable-output-escaping="yes"/>
  </xsl:template>
Related