Re: [xsl] XSLT containing javascript code with '<'

Subject: Re: [xsl] XSLT containing javascript code with '<'
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Sun, 12 Feb 2012 12:33:36 +0100
Wolfgang Laun wrote:

<xsl:stylesheet version="2.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
     xmlns:xs="http://www.w3.org/2001/XMLSchema";
     xmlns="http://www.w3.org/1999/xhtml";>

<xsl:output method = "html" cdata-section-elements="script" encoding =
"UTF-8" indent = "yes"/>

<xsl:template match="/">
<html>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <head>
     <script type="text/javascript"><![CDATA[
function restore(){
    if( 1<  10 )  alert("x");  // something else in reality.
}
]]></script>
     <title>X</title>
   </head>
   <body>
   </body>
</html>
</xsl:template>
</xsl:stylesheet>

However, the output from Saxon 9 (latest) contains
     if( 1&lt; 10 )  alert("x");
which Chrome refuses to accept as correct javascript, and I think it is right.

Omitting cdata-section-elements="script" doesn't alter anything, of course.

For text/html, consider to create HTML 4 or HTML5 with no namespaces with output method "html", then the XSLT processor will serialize inline script correctly for browsers with their tag soup text/html parsers or with their recent move to HTML5 parsers.
You currently have output method "html" which is intended for HTML 4 and text/html with HTML elements being in no namespace, yet your result elements are in the XHTML namespace, so the serialization rules that the output method "html" mandates are not applied to your result elements.


There is also in XSLT 2.0 an output method "xhtml" aimed at outputting XHTML 1.0 as text/html but I don't think it is helpful with inline script. If you really want to create XHTML but want it to be served as text/html then I agree with Andrew that using external script files is the right approach to avoid all these problems with incompatibilites between SGML or tag soup HTML parsing rules and XML serialization syntax.




--


	Martin Honnen --- MVP Data Platform Development
	http://msmvps.com/blogs/martin_honnen/

Current Thread