如何使用XSLT统计单个XML节点内逗号分隔数组的元素数量?
用XSLT统计逗号分隔的XML节点内容的元素数量
针对你这种单个XML节点内存储逗号分隔数组的场景,分XSLT版本给出解决方案:
XSLT 2.0及以上版本(推荐)
XSLT 2.0及更高版本支持tokenize()函数,可以直接将字符串按指定分隔符分割为序列,再用count()统计数量。同时可以用正则表达式处理元素前后的空格:
示例XML输入
<root> <Array>1, 2, 3</Array> </root>
XSLT代码片段
<xsl:template match="/"> <!-- 先去除字符串首尾空格,再按逗号+任意空格分割 --> <xsl:variable name="array-items" select="tokenize(normalize-space(root/Array), ',\s*')"/> 元素数量:<xsl:value-of select="count($array-items)"/> </xsl:template>
输出结果
元素数量:3
normalize-space()会先去掉字符串首尾的空格,同时把中间的连续空格合并成单个,再用,\s*(逗号加任意数量空格)作为分隔符,确保不管元素间有没有空格都能正确分割。
XSLT 1.0版本
XSLT 1.0没有内置的字符串分割函数,需要通过递归模板实现统计逻辑:
示例XML输入
<root> <Array>1, 2, 3</Array> </root>
XSLT代码片段
<!-- 递归统计的模板 --> <xsl:template name="count-comma-items"> <xsl:param name="str"/> <xsl:param name="count" select="0"/> <!-- 先处理当前字符串的首尾空格 --> <xsl:variable name="trimmed-str" select="normalize-space($str)"/> <xsl:choose> <!-- 如果字符串为空,返回当前计数 --> <xsl:when test="$trimmed-str = ''"> <xsl:value-of select="$count"/> </xsl:when> <!-- 如果找不到逗号,说明是最后一个元素,计数+1 --> <xsl:when test="not(contains($trimmed-str, ','))"> <xsl:value-of select="$count + 1"/> </xsl:when> <!-- 找到逗号,递归处理逗号后的部分,计数+1 --> <xsl:otherwise> <xsl:call-template name="count-comma-items"> <xsl:with-param name="str" select="substring-after($trimmed-str, ',')"/> <xsl:with-param name="count" select="$count + 1"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- 主模板调用 --> <xsl:template match="/"> 元素数量: <xsl:call-template name="count-comma-items"> <xsl:with-param name="str" select="root/Array"/> </xsl:call-template> </xsl:template>
输出结果
元素数量:3
这个模板会递归处理字符串,每次找到逗号就分割出前面的元素,计数加1,直到处理完所有元素。normalize-space()同样用来处理空格问题,避免空元素的误统计。
内容的提问来源于stack exchange,提问作者Erik ebsolutions
相关产品推荐
相关产品推荐

