XSLT递归总和麻烦

时间:2011-08-12 17:22:09

标签: xslt recursion sum

当我尝试对来自多个节点的属性进行递归求和时,它就像字符串一样粘贴:(


XML文件(第二里程 - 节点包括第一里程 - 节点)

<mileage value="15000">
    <operation title="Replacing the engine oil" cost="500" />
    <sparepart title="Oil filter" cost="250" />
    <sparepart title="Motor oil" cost="1050" />
</mileage>
<mileage value="30000">
    <repeating mileage="15000" />
    <operation title="Replacement of spark" cost="1200" />
</mileage>

XSL-模板

<xsl:template match="mileage[@value]">
    <xsl:param name="sum" select="number(0)" />
    <xsl:variable name="milinkage"><xsl:value-of select="number(repeating/@mileage)" /></xsl:variable>
    <xsl:apply-templates select="parent::*/mileage[@value=$milinkage]"><xsl:with-param name="sum" select="number($sum)" /></xsl:apply-templates>
    <xsl:value-of select="number(sum(.//@cost))"/> <!--  + number($sum) -->
</xsl:template>

胶合结果是18001200 ,但我想看3000(1800 + 1200) 请告诉我这里有什么问题?

感谢名单!

2 个答案:

答案 0 :(得分:0)

你需要xmlns:exsl =“http://exslt.org/common”

<xsl:template match="/">
    <xsl:variable name="nodes">
        <xsl:apply-templates select="root/mileage[position()=last()]"/>
    </xsl:variable>
    <xsl:copy-of select="sum(exsl:node-set($nodes)/*[@cost]/@cost)"/>
</xsl:template>

<xsl:template match="mileage">
    <xsl:copy-of select="*[@cost]"/>
    <xsl:apply-templates select="../mileage[@value=current()/repeating/@mileage]"/>
</xsl:template>`

答案 1 :(得分:0)

删除点,你将始终看到3000,因为所有@costs(独立于起点)将被加总。

<xsl:value-of select="number(sum(//@cost))"/> <!--  + number($sum) -->

输出如下所示:30003000

但我认为你的方法有问题。当您递归调用模板时,输出也将打印,就像模板在您的情况下调用自身一样。您需要在递归结束时打印出结果

鉴于此输入:

<root>
<mileage value="15000">
    <operation title="Replacing the engine oil" cost="500" />
    <sparepart title="Oil filter" cost="250" />
    <sparepart title="Motor oil" cost="1050" />
</mileage>
<mileage value="30000">
    <repeating mileage="15000" />
    <operation title="Replacement of spark" cost="1200" />
</mileage>
</root>

并使用此xslt:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

<xsl:template match="/">
    <xsl:apply-templates select="root"/>
</xsl:template>

<xsl:template match="root">
    <xsl:apply-templates select="mileage[@value=30000]"/>
</xsl:template>

<xsl:template match="mileage[@value]">
    <xsl:param name="sum" select="number(0)" />
    <xsl:variable name="milinkage"><xsl:value-of select="number(repeating/@mileage)" /></xsl:variable>
    <xsl:variable name="newsum">
        <xsl:value-of select="number(sum(.//@cost)) + $sum"/>
    </xsl:variable>
    <xsl:apply-templates select="parent::*/mileage[@value=$milinkage]"><xsl:with-param name="sum" select="number($newsum)" /></xsl:apply-templates>
    <xsl:if test="not(parent::*/mileage[@value=$milinkage])">
        <xsl:value-of select="$newsum"/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

给出了正确的结果:3000