使用XML的XSLT进行动态数据操作

时间:2010-06-07 06:46:04

标签: xml xslt

我没有使用XSLT太长时间。我读到XSLT的变量无法动态更新,所以我该如何完成以下任务。

我想总结一下购买&销售并将它们放入变量中,并根据这些值做出一些决定。 (例如,如果购买量大于销售额,那么如果没有,则执行其他操作,执行其他操作)

<rows>
    <row>
        <col attr2="Purchase" >100.00</col>
        <col  attr2="Sales" >100.00</col>
    </row>
    <row >
        <col attr2="Purchase" >19.16</col>
        <col  attr2="Sales" >12.94</col>
    </row>
    <row >
        <col attr2="Purchase" >0.67</col>
        <col  attr2="Sales" >2.74</col>
    </row>
    <row >
        <col attr2="Purchase" >71.95</col>
        <col  attr2="Sales" >61.54</col>
    </row>
    <row >
        <col attr2="Purchase" >3.62</col>
        <col  attr2="Sales" >14.72</col>
    </row>
    <row >
        <col attr2="Purchase">8.80</col>
        <col attr2="Sales">1.22</col>
    </row>
    <row >
        <col attr2="Purchase" >-4.28</col>
        <col  attr2="Sales" >6.53</col>
    </row>
</rows>

如果有人知道,请帮助我。

2 个答案:

答案 0 :(得分:1)

XSL变量更常量:一旦设置,它们的值就不能改变。更改变量的唯一方法是使用递归模板,并使用命名参数来保存当前总和。

或者,如果XSLT没有sum函数,你会这么做!

<xsl:variable name="$purchase-total" select="sum(col[@attr2='Purchase'])" />
<xsl:variable name="$sales-total" select="sum(col[@attr2='Sales'])" />
<xsl:choose>
    <xsl:when test="$purchase-total &gt; $sales-total">
        <!-- Do something -->
    </xsl:when>
    <xsl:otherwise>
        <!-- Do something -->
    </xsl:otherwise>
</xsl:choose>

答案 1 :(得分:0)

你可以计算总和,如@Eric的例子所示。

您在评论中提出的问题:要计算x的绝对值,请使用以下XPath表达式:

(x > 0)*x - not(x > 0)*x

例如

使用提供的XML文档

  <xsl:variable name="x" select="(/*/*/col[@attr2='Purchase'])[position()=last()]"/>

  <xsl:value-of select="($x > 0)*$x - not($x > 0)*$x"/>

<强>产生

4.28