Creating CDATA Sections

Creating CDATA Sections

In XML-to-XML transformations, you might want to output CDATA sections. XSLT makes it easy to do that with the <xsl:output> elements cdata-section-elements attribute. This attribute enables you to indicate which elements content should be enclosed in a CDATA section. Thats useful, for example, when youre creating script elements and want to deal with a browser that requires script code to be inside a CDATA section.

In the following example, I place the contents of the < NAME > and <MASS> elements in planets.xml in CDATA sections:

 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  <xsl:output method="xml" cdata-section-elements="NAME MASS"/>    <xsl:template match="@*node()">      <xsl:copy>        <xsl:apply-templates select="@*node()"/>      </xsl:copy>    </xsl:template>  </xsl:stylesheet> 

And heres the result:

 <?xml version="1.0" encoding="UTF-8"?>  <?xml-stylesheet type="text/xml" href="planets.xsl"?>  <PLANETS>      <PLANET>          <NAME><![CDATA[Mercury]]></NAME>          <MASS UNITS="(Earth = 1)"><![CDATA[.0553]]></MASS>          <DAY UNITS="days">58.65</DAY>          <RADIUS UNITS="miles">1516</RADIUS>          <DENSITY UNITS="(Earth = 1)">.983</DENSITY>          <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->      </PLANET>      <PLANET>          <NAME><![CDATA[Venus]]></NAME>          <MASS UNITS="(Earth = 1)"><![CDATA[.815]]></MASS>          <DAY UNITS="days">116.75</DAY>          <RADIUS UNITS="miles">3716</RADIUS>          <DENSITY UNITS="(Earth = 1)">.943</DENSITY>          <DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->      </PLANET>          .          .          . 

Handling Source Versus Result CDATA

This technique generates CDATA sections in the result document; it does not treat any data in the source document as CDATA. For example, if you want to transform <script>if x < y {...}</script> into <script><![CDATA[if x < y {...}]]></script> because your browser requires script code to be in CDATA sections, the XSLT processor will have trouble with the unescaped < in x < y. In this case, you must use <script>if x &lt; y {...}</script> so the XSLT processor will generate <script><![CDATA[if x <y {...}]]></script>.



Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
EAN: N/A
Year: 2005
Pages: 196

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net