1

让我的头脑卡在一些简单的 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
4

1 回答 1

0

简而言之,答案是使用sum()带有 XSL 键和<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
于 2013-02-18T18:49:13.403 回答