Insert JavaScript in XSLT Document

Q

How to insert JavaScript code in XSLT and to be generated in the output in XML format?

✍: FYIcent

A

Inserting JavaScript code in XSLT and keep it in the XML output correctly is a very challenging task:

  1. You need to find a way to enter and protect special characters like, <, > and & in the input file.
  2. You need to find a way to keep those special characters from be escaped in the output file.
  3. You need to keep JavaScript code inside CDATA in the output file to be a valid XML document.
  4. You need to code CDATA tags as JavaScript comments

But this is doable. Try the following XSLT code:

<xsl:text disable-output-escaping="yes"><![CDATA[
<script type="text/javascript">
//<![CDATA[
   if ( a<x && x<b) ...
//]]>]]>
</script>
</xsl:text>

You should get this output, which is still a perfect XML document:

<script type="text/javascript">
//<![CDATA[
   if ( a<x && x<b) ...
//]]>
</script>

2015-10-26, 1719🔥, 0💬