javascript块中的XSLT参数返回不正确的值

XSLT param returns incorrect value in javascript block

本文关键字:返回 不正确 参数 XSLT javascript      更新时间:2023-09-26

我正在传递参数值作为目录说c:'MyFolder'myfile.txt。

但是当我在javascript块中接收到这个值时它返回值c: myfoldermyfile。txt

我将如何获得相同的参数值在javascript块?

代码:

<xsl:param name="ResourcePath"/>
<xsl:template match="/">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>    
        <script type="text/javascript">
           alert('<xsl:value-of select="$ResourcePath"/>');
           //It shows value c:MyFolderMyfile.txt but I want c:'MyFolder'myfile.txt
        </script>
      </head>
      <body> </body>
    </html>
  </xsl:template>

要在JavaScript中工作,而不是输出这个…

alert('c:'MyFolder'myfile.txt');

你需要输出这个

alert('c:''MyFolder''myfile.txt');

遗憾的是,XSLT 1.0没有"替换"函数,因此您必须使用递归模板将'替换为''

在StackOverflow上快速搜索发现如下示例:

XSLT字符串替换

试试这个XSLT,它包含了"replace"模板

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output omit-xml-declaration="yes" indent="yes" />
   <xsl:param name="ResourcePath" select="'c:'MyFolder'myfile.txt'"/>
   <xsl:template match="/">
     <html xmlns="http://www.w3.org/1999/xhtml">
       <head>    
         <script type="text/javascript">
            <xsl:text>alert('</xsl:text>
        <xsl:call-template name="string-replace-all">
               <xsl:with-param name="text" select="$ResourcePath" />
               <xsl:with-param name="replace" select="'''" />
               <xsl:with-param name="by" select="''''" />
            </xsl:call-template>
            <xsl:text>');</xsl:text>
         </script>
       </head>
       <body> </body>
     </html>
   </xsl:template>
   <xsl:template name="string-replace-all">
     <xsl:param name="text" />
     <xsl:param name="replace" />
     <xsl:param name="by" />
     <xsl:choose>
       <xsl:when test="contains($text, $replace)">
         <xsl:value-of select="substring-before($text,$replace)" />
         <xsl:value-of select="$by" />
         <xsl:call-template name="string-replace-all">
           <xsl:with-param name="text" select="substring-after($text,$replace)" />
           <xsl:with-param name="replace" select="$replace" />
           <xsl:with-param name="by" select="$by" />
         </xsl:call-template>
       </xsl:when>
       <xsl:otherwise>
         <xsl:value-of select="$text" />
       </xsl:otherwise>
     </xsl:choose>
   </xsl:template>
</xsl:stylesheet>

这应该输出如下

<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <script type="text/javascript">alert('c:''MyFolder''myfile.txt');</script>
   </head>
   <body/>
</html>

您需要在$ResourcePath中转义斜杠。将此处的文本:c:'MyFolder'myfile.txt替换为:c:''MyFolder''myfile.txt

JavaScript将字符串中的'解释为转义字符。由于斜杠后面跟着一个m,这会导致无效的转义序列,因此它只呈现m而不是'm