How to include Javascript in xml-document?

前端 未结 7 1575
醉酒成梦
醉酒成梦 2020-12-01 07:59

The task seems to be pretty easy: how to include a Javascript file in xml-document so that at least Opera and Firefox could actually parse it and execute the code?

相关标签:
7条回答
  • 2020-12-01 08:53

    Similar to the above, but that could error because the <![CDATA[ and ]]> portions are not valid code. If you're putting it into an XSL script, you can just as well put a JS comment mark before these beginning and ending elements.

    I also have used the xsl:text element to output the <![CDATA[ portion. This portion may be a bit of cheat, but it results in well-formed XML. An example from within an xsl:choose block might be...

    ...
    <xsl:when test='name()="script"'>
      <script>
        <xsl:for-each select='@*'><xsl:copy-of select='.' /></xsl:for-each>
        <xsl:text disable-output-escaping='yes'>
    // &lt;![CDATA[
      </xsl:text>
      <xsl:copy-of select='./text()' />
      <xsl:text disable-output-escaping='yes'>
    //]]&gt;
      </xsl:text>
      </script>
    </xsl:when>
    ...
    

    Walking through the pieces...

    1. Detect a <script> element.
    2. Replicate <script> tag for the output.
    3. Be sure to preserve the tag attributes in the output with a quick xsl:for-each line.
    4. Output the non-escaped text: // <![CDATA[. The // renders the rest of the line as a comment and thus prevents a JS error.
    5. Copy the text contents of the <script> tag. NOTE: You must preseve the new-line (either as above or some other way) so that the commented out line before it does not end up on the same line as this one. Obviously, if it does, it will comment out this line as well. Preserving the one after is not essential, but is keeps the aesthetics of the two matching CDATA tags.
    6. Output the non-escaped text: // ]]>. This ends the CDATA block, and again, the CDATA marking is ignored by the browser when reading the JS.
    7. Close the block with a </script> tag, of course.
    8. And, if you're using it in a xsl:choose block, close then xsl:when.

    Only steps 2, 3, 5, & 7 actually copy the script block. The rest is busywork to make it work.

    Transforming a block such as...

    ...
    <script type='javascript'>alert('Hello World!');</script>
    ...
    

    Then becomes,

    ...
    <script type='javascript'>
    // <![CDATA[
    alert('Hello World!');
    // ]]>
    </script>
    

    Effectively preserved, and readable both by XML as well as a browser.

    0 讨论(0)
提交回复
热议问题