XSLT2脚本求助:从变量构造指定参数的URL失败
XSLT2构造指定参数URL的问题解决
问题描述
我正在编写XSLT2脚本,其中变量包含如下文本:
<xsl:variable name="urlparams" select="'color=red;rating=5;page=8;product=xyz'"/>
需要构造出类似这样的URL(等号后的取值为动态可变,比如color=blue或product=abc):
<a href="www.google.com/?color=red&product=xyz"/>
但我编写的XSLT脚本无法正常工作,代码如下:
<xsl:template match="/"> <xsl:variable name="urlparams" select="'color=red;rating=5;page=8;product=xyz'"/> <xsl:value-of select="'www.google.com/?'"/> <xsl:for-each select="tokenize($urlparams, ';')"> <xsl:if test=". = 'color'"> <xsl:value-of select="."/><xsl:text>&amp;</xsl:text> </xsl:if> <xsl:if test=". = 'product'"> <xsl:value-of select="."/> </xsl:if> </xsl:for-each> </xsl:template>
问题分析
你的代码存在两个核心问题:
- 条件判断逻辑错误:
test=". = 'color'"是判断当前token是否等于纯字符串color,但实际每个token是color=red这类完整键值对,永远无法匹配,导致没有输出内容。 - 转义符使用错误:URL参数的分隔符
&在XML中需转义为&,但你用了&amp;,会导致最终输出&而非正确的&。
解决方案
方案一:简洁版(使用string-join)
通过tokenize拆分参数后直接筛选目标键值对,再用string-join拼接,代码更简洁:
<xsl:template match="/"> <xsl:variable name="urlparams" select="'color=red;rating=5;page=8;product=xyz'"/> <!-- 拆分参数并筛选出color和product开头的键值对 --> <xsl:variable name="selected-params" select="tokenize($urlparams, ';')[starts-with(., 'color=') or starts-with(., 'product=')]"/> <!-- 拼接成合法URL参数,XML中用&表示& --> <a href="www.google.com/?{string-join($selected-params, '&')}"/> </xsl:template>
方案二:灵活配置版(支持动态调整允许的参数)
如果需要后续灵活修改允许保留的参数,可以定义参数列表变量,通过提取键名来筛选:
<xsl:template match="/"> <xsl:variable name="urlparams" select="'color=red;rating=5;page=8;product=xyz'"/> <!-- 定义允许保留的参数键名 --> <xsl:variable name="allowed-keys" select="('color', 'product')"/> <xsl:variable name="selected-params"> <xsl:for-each select="tokenize($urlparams, ';')"> <!-- 提取当前参数的键名 --> <xsl:variable name="current-key" select="substring-before(., '=')"/> <xsl:if test="$current-key = $allowed-keys"> <xsl:value-of select="."/> <!-- 仅在非最后一个参数后添加分隔符 --> <xsl:if test="position() != last()"> <xsl:text>&</xsl:text> </xsl:if> </xsl:if> </xsl:for-each> </xsl:variable> <a href="www.google.com/?{$selected-params}"/> </xsl:template>
内容的提问来源于stack exchange,提问作者user19732805
相关产品推荐
相关产品推荐

