Embed HTML Script in XSLT
Written by
Gregory Scot Collins
Thursday, 11 May 2006, 6:48 AM
This article has been tested to work with the following products and versions. No guarantee of compatibility, with or without modification, is offered for products or versions other than those listed.
- JavaScript 1.7 (Netscape Communications)
- HTML 4.01 (W3C)
- XSLT 1.0 (W3C)
IN THIS ARTICLE:
When transforming to an HTML document that includes script you might encounter an error because code typically contains characters considered illegal to XML parsers (see Table 1). These characters must either be manually escaped or contained within a CDATA section. All content within a CDATA section is ignored by the parser, meaning it will be interpreted strictly as text and not as markup, thus automatically escaping the characters listed in rows 1-3 of Table 1.
| Row | Character | Entity Reference | Name |
|---|---|---|---|
| 1 | < | < | Less Than |
| 2 | & | & | Ampersand |
| 3 | > | > | Greater Than |
| 4 | ' | ' | Apostraphe |
| 5 | " | " | Quotation Mark |
Table 1.
The five predefined XML entity references.
The characters in the first two rows of Table 1 are strictly illegal in XML, meaning that they must be escaped either manually by substitution with their associated entity reference, or by inclusion within a CDATA section. This is because the parser interprets the < character as the start of a new element, and the & character as the start of a character escape sequence. While it is not required that the remaining three characters be escaped, it is considered a best practice to do so.
How to use a CDATA section
A CDATA section begins with <![CDATA[ and ends with ]]>. Listing 1 is an example of how to correctly use a CDATA section to output a block of JavaScript code from a transform:
Output markup within a CDATA section
Since CDATA sections are used to escape blocks of text containing characters that would otherwise be recognized as markup, if follows that you cannot output XML values directly within the CDATA section as you would elsewhere. For example, an <xsl:value-of/> tag would be interpreted as text, thus frustrating your intentions. To accomplish this you must explicitly close the CDATA section, include your markup, and then reopen the CDATA section, as shown in Listing 2:
Copyright ©2006
Braintrove. All rights reserved. This material may not be copied, published, broadcast, rewritten
or redistributed. You may, however, use the techniques, along with any associated code and files in
your development. This material is provided "AS IS" without warranty of any kind. You accept full
responsibility and liability for any and all results associated with use of this material.
Stumble It!
Digg It!
del.icio.us




