You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;amp;</xsl:text>
            </xsl:if>
            <xsl:if test=". = 'product'">
                <xsl:value-of select="."/>
            </xsl:if>
        </xsl:for-each>

 </xsl:template>

问题分析

你的代码存在两个核心问题:

  1. 条件判断逻辑错误:test=". = 'color'"是判断当前token是否等于纯字符串color,但实际每个token是color=red这类完整键值对,永远无法匹配,导致没有输出内容。
  2. 转义符使用错误:URL参数的分隔符&在XML中需转义为&amp;,但你用了&amp;amp;,会导致最终输出&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中用&amp;表示& -->
    <a href="www.google.com/?{string-join($selected-params, '&amp;')}"/>
</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>&amp;</xsl:text>
                </xsl:if>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>
    <a href="www.google.com/?{$selected-params}"/>
</xsl:template>

内容的提问来源于stack exchange,提问作者user19732805

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:25:57