XSLT字符串解析

3

我对以下“PrimarySubject”中的XSLT不熟悉,我需要将其包含的'&'字符替换为%26并将' '字符替换为%20。

<xsl:template name="BuildLink"> 
    <xsl:param name="PrimarySubject" /> 
    <xsl:text>?PrimarySubject=</xsl:text> 
    <xsl:value-of select="$PrimarySubject" /> 
</xsl:template> 

在XSLT版本1中是否有可用的字符串替换函数?谢谢。


啊,我明白了,你试着用 XSLT 实现 URI 编码器,不错嘛 ;-) - Boldewyn
2个回答

3

最简单的方法是使用FXSL库,更准确地说是使用它的str-map模板。

这里有一个简单的例子。

这个转换:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl testmap"
>
   <xsl:import href="str-map.xsl"/>

   <!-- to be applied on any xml source -->

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select="'abc&amp;d f'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template match="testmap:*">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="$arg1 = '&amp;'">%26</xsl:when>
       <xsl:when test="$arg1 = ' '">%20</xsl:when>
       <xsl:otherwise><xsl:value-of select="$arg1"/></xsl:otherwise>
      </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

应用于任何 XML 文档(未使用),会产生所需的结果: abc%26d%20f

1
最好使用别人编写的库,在“我没有考虑到的情况”中节省一些时间。 - Nat
@Nat,当然,FXSL的用户很少需要自己实现递归。 - Dimitre Novatchev
@infant-programmer 很高兴见到你,你在评论中的"[15 chars]"是什么意思? - Dimitre Novatchev
非常感谢。我还有一个问题,如何将vTestMap的值作为参数传递给另一个模板?我尝试了下面的方法,但它不起作用... <xsl:call-template name="BuildLink"> <xsl:with-param name="PrimarySubject" select="$vTestMap" /> </xsl:call-template> - van
@nav 我回答中的代码已经将 $vTestMap 作为参数传递了...你的代码肯定有问题,但是如果没有看到代码,就很难猜测出错在哪里(至少对我来说是这样)。 - Dimitre Novatchev
抱歉,你的代码没有起作用。这只是与SharePoint一起工作的微妙之处,我无法使用此解决方案。由于导入语句出现错误,否则这对我来说本来可以起作用 :) - van

0

XSLT中有多个子字符串函数:

  • string substring-before(string, string)
  • string substring-after(string, string)
  • string substring(string, number, number?)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接