在XSL中包含带有大括号{}的内联JavaScript

Include Inline JavaScript with Curly Brackets {} in XSL

本文关键字:JavaScript XSL 包含带      更新时间:2023-09-26

我正在尝试通过XSL文件将XML转换为HTML。不幸的是,它不允许我使用JavaScript大括号{}。下面是一个简单的例子,但是我的实际代码要大得多。

<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:output media-type="text/html; charset=UTF-8" encoding="UTF-8"/>
    <xsl:template match='/'>
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <title> Page Title</title>
            </head>
            <body onload="javascript: if(confirm('Are you sure?')) { return true;} else { return false;}">
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Visual Studio给出以下错误:

Expected token '}', found 'true'.  ...firm('Are you sure?')) { return  -->true<-- ;} else { return false;}  

是否有办法在XSL中包含内联JavaScript ?我知道您可以使用<![CDATA[ ]]>来转义Javascript块。但是如何转义内联JavaScript呢?我的实际代码太大,无法将所有内联JavaScript重写为脚本块。

文本结果元素属性中的花括号用于"属性值模板",包含XPath表达式。因此,如果您想生成包含卷发的属性,您需要通过将它们加倍来转义它们:

<body onload="javascript: if(confirm('Are you sure?')) {{ return true;}} else {{ return false;}}">

然而,在onXXX属性中包含大块的Javascript可能是最好避免的:相反,只包含一个函数调用在<script>中定义的代码。

试试这个,它应该不需要转义:

<body>
  <xsl:attribute name="onload">
    javascript: if(confirm('Are you sure?')) { return true;} else { return false;}
  </xsl:attribute>
</body>