XSLT中统计数组内指定元素出现次数的实现问题
问题原因
- 原有代码中
count($array/Item='A')的逻辑错误:$array/Item='A'返回的是布尔值(只要存在符合条件的节点就返回true,否则返回false),对布尔值执行count操作永远得到1,无法统计匹配数量。 - 额外注意:你定义的
$array变量本身就是Item元素的序列,不需要再加/Item路径二次查找。
可行实现方案
直接筛选出值等于A的Item元素后统计数量即可,修正后的核心统计代码为:
<xsl:value-of select="count($array[. = 'A'])"/>
完整修正后代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:array="http://www.w3.org/2005/xpath-functions/array" exclude-result-prefixes="#all" version="3.0"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:param name="input"/> <xsl:variable name="newline" select="' '"/> <xsl:template match="/" name="xsl:initial-template"> <xsl:variable name="input-as-map" select="parse-json($input)" as="map(*)"/> <root> <!-- storing all the PERSONNUMBER present in the ibop --> <xsl:variable name="array" as="element()*"> <Item>A</Item> <Item>A</Item> <Item>A</Item> <Item>b</Item> </xsl:variable> <test> <xsl:value-of select="count($array[. = 'A'])"/> </test> </root> </xsl:template> </xsl:stylesheet>
运行后输出的<test>节点值为3,符合预期。
额外补充说明
如果你后续需要统计标准XPath 3.0数组类型(而非当前的元素序列)中的值出现次数,可以用如下写法:
<!-- 示例数组,比如从parse-json得到的数组 --> <xsl:variable name="json-array" select="array{'A','A','A','b'}" as="array(*)"/> <!-- 统计A的出现次数 --> <xsl:value-of select="count($json-array?*[. = 'A'])"/>
内容的提问来源于stack exchange,提问作者vivek
相关产品推荐
相关产品推荐

