XML节点排序与统计需求:按时间升序、品牌分组并计数样本及状态
嘿,我来帮你搞定这个XML数据处理的需求!要实现按品牌分组、时间升序排序,还要统计每组的样本数和trend的真假数量,用XSLT来处理是最直接的方案,下面一步步来:
步骤1:明确需求拆解
先把需求拆成可落地的细节:
- 把所有
<car>节点按brand属性分组,同品牌的归为一组 - 每组内的节点按
time属性数值升序排列 - 对每个分组,基于组内最小的
time(也就是分组起始时间),统计三个核心数据:- 该组的车辆样本总数
trend="true"的样本数量trend="false"的样本数量
步骤2:编写XSLT处理脚本
下面是可直接运行的XSLT代码,每部分都加了注释说明:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- 按brand属性创建分组索引,快速定位同品牌车辆 --> <xsl:key name="carByBrand" match="car" use="@brand"/> <xsl:template match="/trade"> <result> <!-- 遍历每个唯一的品牌分组 --> <xsl:for-each select="car[generate-id() = generate-id(key('carByBrand', @brand)[1])]"> <xsl:variable name="currentBrand" select="@brand"/> <!-- 获取当前品牌的所有车辆节点 --> <xsl:variable name="groupCars" select="key('carByBrand', $currentBrand)"/> <!-- 提取组内最小的time(起始时间) --> <xsl:variable name="startTime" select="$groupCars/@time[not(. > $groupCars/@time)]"/> <brand-group brand="{$currentBrand}" start-time="{$startTime}"> <!-- 统计组内总样本数 --> <total-count><xsl:value-of select="count($groupCars)"/></total-count> <!-- 统计trend为true的样本数 --> <trend-true-count><xsl:value-of select="count($groupCars[@trend='true'])"/></trend-true-count> <!-- 统计trend为false的样本数 --> <trend-false-count><xsl:value-of select="count($groupCars[@trend='false'])"/></trend-false-count> <!-- 可选:输出组内按time升序排序后的车辆节点 --> <sorted-cars> <xsl:for-each select="$groupCars"> <xsl:sort select="@time" data-type="number" order="ascending"/> <xsl:copy-of select="."/> </xsl:for-each> </sorted-cars> </brand-group> </xsl:for-each> </result> </xsl:template> </xsl:stylesheet>
步骤3:处理结果示例
假设你提供的完整XML是:
<?xml version="1.0" encoding="UTF-8"?> <trade> <car time="1950" brand="audi" trend="true"> </car> <car time="1200" brand="renault" trend="true"> </car> <car time="1000" brand="audi" trend="true"> </car> <car time="2800" brand="renault" trend="false"> </car> <car time="2000" brand="audi" trend="false"> </car> </trade>
经过上述XSLT处理后,会得到结构化的统计结果:
<?xml version="1.0" encoding="UTF-8"?> <result> <brand-group brand="audi" start-time="1000"> <total-count>3</total-count> <trend-true-count>2</trend-true-count> <trend-false-count>1</trend-false-count> <sorted-cars> <car time="1000" brand="audi" trend="true"> </car> <car time="1950" brand="audi" trend="true"> </car> <car time="2000" brand="audi" trend="false"> </car> </sorted-cars> </brand-group> <brand-group brand="renault" start-time="1200"> <total-count>2</total-count> <trend-true-count>1</trend-true-count> <trend-false-count>1</trend-false-count> <sorted-cars> <car time="1200" brand="renault" trend="true"> </car> <car time="2800" brand="renault" trend="false"> </car> </sorted-cars> </brand-group> </result>
内容的提问来源于stack exchange,提问作者Jakub Oškera
相关产品推荐
相关产品推荐

