这是我的XML样本,它可能包含数千种不同类别的项目。
<store>
<products type="computer">
<item desc="text" amount="99"></c>
<item desc="text" amount="69.95"></c>
<item desc="text" amount="4.50"></c>
<item desc="text" amount="10"></c>
<item desc="text" amount="9.99"></c>
<item desc="text" amount="24"></c>
</products>
<products type="books">
<item desc="text" amount="5"></c>
<item desc="text" amount="9.99"></c>
<item desc="text" amount="24"></c>
</products>
<products type="music">
<item desc="text" amount="5"></c>
<item desc="text" amount="1"></c>
<item desc="text" amount="4.50"></c>
<item desc="text" amount="10"></c>
<item desc="text" amount="9.99"></c>
</products>
</store>
我想要的是某种循环,它允许我为每100个项目创建一个标题,而不管产品类型如何。这很容易但是在这个标题中我想要直接在该标题下的100个项目的总和。
目前我已尝试将树分成100个组,因此我可以对每个组执行求和功能。我已经在这个问题上待了几天但是我没能提供完整的解决方案。
我的输出看起来像这样(如果n是3):
Header Total=173.45
text,99
text,69.95
text,4.50
Header Total=43.99
text,10
text,9.99
text,24
Header Total=38.99
text,5
text,9.99
text,24
Header Total=10.50
text,5
text,1
text,4.50
Header Total=19.99
text,10
text,9.99
答案 0 :(得分:0)
可能不是最有效的方法,但这是一种方式:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8"/>
<xsl:variable name="newline" select="'
'" />
<xsl:variable name="items" select="//item" />
<xsl:variable name="items-count" select="count($items)" />
<xsl:variable name="loop-size" select="3" />
<xsl:template match="/">
<xsl:call-template name="group-sum" />
</xsl:template>
<xsl:template name="group-sum">
<xsl:param name="position" select="1" />
<xsl:param name="sum" select="0" />
<xsl:param name="group" select="''" />
<xsl:variable name="current" select="$items[$position]" />
<xsl:if test="$position != 1 and
(($position - 1) mod $loop-size = 0 or $position = $items-count + 1)">
<xsl:value-of select="concat('Header Total=', $sum, $newline, $group)" />
</xsl:if>
<xsl:choose>
<xsl:when test="$position != 1 and ($position - 1) mod $loop-size = 0">
<!-- Start a new group -->
<xsl:call-template name="group-sum">
<xsl:with-param name="position" select="$position + 1" />
<xsl:with-param name="sum" select="$current/@amount" />
<xsl:with-param name="group" select="concat($current/@desc, ',', $current/@amount, $newline)" />
</xsl:call-template>
</xsl:when>
<xsl:when test="$position <= $items-count">
<!-- Append to the current group -->
<xsl:call-template name="group-sum">
<xsl:with-param name="position" select="$position + 1" />
<xsl:with-param name="sum" select="$sum + $current/@amount" />
<xsl:with-param name="group" select="concat($group, $current/@desc, ',', $current/@amount, $newline)" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<!-- Finished -->
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
干杯 卡洛斯