Search code examples
htmlxmlxsltescapingscript-tag

Escape the content inside a <script> tag


I want to store XSLT code in a HTML file like that:

<script id="xsltCode" type="text/xml">
  <?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    ...
      <script>...</script>
    ...
  </xsl:stylesheet>
</script>

As you can see, the problem I have is caused by the <script> tag inside the XSLT code. What is the simplest solution to escape it?

Thank you for your help.


Solution

  • Throwing arbitrary tags in there isn't really advisable. If you can't load the XSLT separately, alternatives are:

    • Store it in a JavaScript string (cleanest option)
    • Properly escape the XSLT:
      • < needs to be escaped with &lt;
      • Any XML entity escapes already existing in your XSLT need to be double-escaped. E.g. if there is an &amp; or a numeric escape like &#10;, turn those into &amp;amp; and &amp;#10;.
    • Use XHTML where mixing in other XML is not a problem. (However, you have to serve it with the correct mimetype and make sure you work cleanly. This is a clean but "old-fashioned" solution.)

    In any case, leave out the XML declaration. It doesn't make sense here and could even cause problems.