返回每天或每个产品的总销售额和平均销售额

时间:2013-02-18 18:33:01

标签: xslt

让我的头脑卡在一些简单的XSL函数上。我需要从这个XML返回每个产品的总销售额和平均销售额以及每天的总销售额。

<products>
    <product>
        <id>1</id>
        <brand>Samsung</brand>  
        <model>Galaxy</model>
        <serialno>00345234</serialno>
        <sales>
            <sale day="20130211">1200</sale>
            <sale day="20130212">9000</sale>
            <sale day="20130213">5400</sale>
        </sales>
    </product>
    <product>
        <id>2</id>
        <brand>Sony</brand> 
        <model>Bravia</model>
        <serialno>07432200</serialno>
        <sales>
            <sale day="20130211">3400</sale>
            <sale day="20130212">990</sale>
            <sale day="20130213">1400</sale>
        </sale>
    </product>
</products>

输出

Total sales per day: 21390
Total (S/N 00345234): 15600
Average (S/N 00345234): 5200
Total (S/N 07432200): 5790
Average (S/N 07432200): 1930
Total sales for day 20130212 = 9990
Total sales for day 20130213 = 6800
Total sales for day 20130211 = 4600

1 个答案:

答案 0 :(得分:0)

简而言之,答案是使用带有XSL密钥和sum()元素的<xsl:sort>函数。此XSLT 1.0兼容示例可能会帮助您入门:

<强>样式表

<?xml version="1.0" encoding="iso-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <!-- Index <sale> elements using the @day attribute -->
  <xsl:key name="kSale" match="sale" use="@day"/>

  <xsl:template match="product">
    <xsl:variable name="serialNo" select="serialno"/>
    <!-- Add together all sales for today. -->
    <xsl:variable name="totalSales" select="sum(sales/sale)"/>
    <!-- Divide total sales by the amount of sales. -->
    <xsl:variable name="averageSales" select="$totalSales div count(sales/sale)"/>
    Total (S/N <xsl:value-of select="$serialNo"/>): <xsl:value-of select="$totalSales"/>
    Average (S/N <xsl:value-of select="$serialNo"/>): <xsl:value-of select="$averageSales"/>
  </xsl:template>

  <xsl:template match="sale">
    <!--
    Get the total sales for this day by adding together the values of all <sale>
    elements with the same @day attribute as this one.
    -->
    <xsl:variable name="totalSalesForDay" select="sum(key('kSale', @day))"/>
    Total sales for day <xsl:value-of select="@day"/>: <xsl:value-of select="$totalSalesForDay"/>
  </xsl:template>

  <xsl:template match="/">
    <xsl:apply-templates select="products/product"/>
    <xsl:apply-templates select="products/product[1]/sales/sale">
      <!-- Sort the sales per day in descending order. -->
      <xsl:sort select="." order="descending" data-type="number"/>
    </xsl:apply-templates>
  </xsl:template>
</xsl:stylesheet>

<强>输出

Total (S/N 00345234): 15600
Average (S/N 00345234): 5200
Total (S/N 07432200): 5790
Average (S/N 07432200): 1930
Total sales for day 20130212: 9990
Total sales for day 20130213: 6800
Total sales for day 20130211: 4600