如何使用XSLT将amount属性分为两类并存储为变量?
解决XML中amount属性分类统计的问题
问题根源
你的代码存在三个核心问题:
- XML示例无
pc:命名空间前缀,代码里的pc:number、pc:description路径无效 - 直接用字符串比较属性值,会导致数值逻辑错误(比如字符串"99999"会被判定为大于"100000")
- 节点路径不匹配XML结构,正确路径应为
result/high/numbers/number/description
修正后的代码实现
1. 统计两类数量的变量定义
如果只需统计数量:
<!-- 统计amount ≤100000的low类数量 --> <xsl:variable name="low_count" select="count(result/high/numbers/number/description[number(@amount) <= 100000])" /> <!-- 统计amount >100000的high类数量 --> <xsl:variable name="high_count" select="count(result/high/numbers/number/description[number(@amount) > 100000])" />
2. 保存节点集合的变量定义
如果需要后续对节点进行其他操作,直接保存节点集:
<!-- 保存所有low类的description节点 --> <xsl:variable name="low_nodes" select="result/high/numbers/number/description[number(@amount) <= 100000]" /> <!-- 保存所有high类的description节点 --> <xsl:variable name="high_nodes" select="result/high/numbers/number/description[number(@amount) > 100000]" /> <!-- 后续可通过count($low_nodes)获取数量 -->
完整可运行的XSLT示例
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <xsl:variable name="low_count" select="count(result/high/numbers/number/description[number(@amount) <= 100000])" /> <xsl:variable name="high_count" select="count(result/high/numbers/number/description[number(@amount) > 100000])" /> low类数量: <xsl:value-of select="$low_count" /> high类数量: <xsl:value-of select="$high_count" /> </xsl:template> </xsl:stylesheet>
针对你提供的XML示例,运行后会输出:
low类数量: 0
high类数量: 3
内容的提问来源于stack exchange,提问作者Rina
相关产品推荐
相关产品推荐

