URL查询参数提取:参数顺序不固定时如何获取gcode的值?
解决XSLT中提取任意位置查询参数的问题
这个问题确实很典型——URL查询参数的顺序本来就没有固定要求,之前的写法硬依赖gcode后面跟着&pcode=,一旦参数顺序变了或者换了其他参数,就彻底失效了。我分不同XSLT版本给你提供靠谱的解决方案:
XSLT 1.0 解决方案(兼容旧环境)
因为XSLT 1.0没有内置的字符串分割函数,我们需要用递归模板来遍历所有查询参数,找到目标参数后提取对应的值:
第一步:定义提取参数的递归模板
<xsl:template name="extract-query-param"> <!-- 传入查询参数字符串(问号后面的部分) --> <xsl:param name="query-str"/> <!-- 传入要提取的参数名 --> <xsl:param name="target-param"/> <xsl:choose> <!-- 情况1:查询字符串为空,直接返回空 --> <xsl:when test="$query-str = ''"/> <!-- 情况2:当前第一个参数就是目标参数 --> <xsl:when test="starts-with($query-str, concat($target-param, '='))"> <!-- 提取等号后面的值,直到遇到下一个&(如果是最后一个参数,就取到字符串末尾) --> <xsl:value-of select="substring-before(concat($query-str, '&'), '&')"/> <xsl:value-of select="substring-after(., '=')"/> </xsl:when> <!-- 情况3:当前参数不是目标,去掉第一个参数后递归处理剩余部分 --> <xsl:otherwise> <xsl:call-template name="extract-query-param"> <xsl:with-param name="query-str" select="substring-after($query-str, '&')"/> <xsl:with-param name="target-param" select="$target-param"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template>
第二步:调用模板提取gcode
<!-- 先从URL中分离出查询参数字段 --> <xsl:variable name="query-part" select="substring-after($currentURI, '?')"/> <!-- 调用模板提取gcode的值 --> <xsl:call-template name="extract-query-param"> <xsl:with-param name="query-str" select="$query-part"/> <xsl:with-param name="target-param" select="'gcode'"/> </xsl:call-template>
XSLT 2.0/3.0 解决方案(更简洁)
如果你的环境支持XSLT 2.0及以上版本,就可以利用tokenize()函数直接分割查询参数,代码会简洁很多:
<!-- 分离查询参数字段 --> <xsl:variable name="query-part" select="substring-after($currentURI, '?')"/> <!-- 提取gcode的值:分割参数后筛选出以gcode=开头的项,再取等号后面的内容 --> <xsl:variable name="gcode-value" select=" substring-after( tokenize($query-part, '&')[starts-with(., 'gcode=')], '=' ) "/> <!-- 使用时直接输出即可 --> <xsl:value-of select="$gcode-value"/>
注意边界情况
- 如果URL中没有
gcode参数,以上两种方案都会返回空字符串,不会报错; - 如果
gcode是最后一个参数,代码会自动取到字符串末尾,不需要额外处理; - 若参数值中包含编码后的
%26(即原始的&),不用担心,因为tokenize()是按未编码的&分割,不会破坏参数值。
内容的提问来源于stack exchange,提问作者user5458829
相关产品推荐
相关产品推荐

