for-each 循环中的 XSLT 变量总和不起作用?

XSLT sum of variables in for-each loop doesn't work?

我需要在for-each循环中打印多个数字的总和,我尝试了这种语法,因为如果之前没有解析,数字将无法添加,但结果永远为0,即使变量$result是正确的数字。

这是我的语法:

<xsl:variable name="sum" select="0" />
<xsl:for-each select="Details/Package/Items">
 <xsl:variable name="int" select="substring-before(IWeight,',')"/>
 <xsl:variable name="dec" select="substring-after(IWeight, ',')"/>
 <xsl:variable name="result" select="number(concat($int,'.',$dec))"/>
 <xsl:variable name="sum" select="$sum + $result" />
</xsl:for-each>
<xsl:value-of select="$sum"/>

我不明白为什么它不起作用。谁能帮帮我,THX!

  <Details>
   <Package>
    <Items>
     <ItemSeqNo>1</ItemSeqNo>
     <Type>0</Type>
     <INumber>1</INumber>
     <IWeight>1,000</IWeight>
     <IDescription>A</IDescription>
     <Length>010</Length>
     <Height>030</Height>
     <Width>020</Width>
    </Items>
    <Items>
     <ItemSeqNo>2</ItemSeqNo>
     <Type>0</Type>
     <INumber>1</INumber>
     <IWeight>2,500</IWeight>
     <IDescription>B</IDescription>
     <Length>020</Length>
     <Height>040</Height>
     <Width>030</Width>
    </Items>
    <TotalPieces>2</TotalPieces>
    <TotalWeight>3,500</TotalWeight>
    <TotalVolume>0,030</TotalVolume>
   </Package>
  </Details>

您不能在 XSLT 中重新定义变量。你的 $sum 变量被定义为 0 并且不能被重新定义。

如果您不重复使用 $sum 变量,您的代码可以正常工作。

<xsl:template match="/">
    <xsl:for-each select="Details/Package/Items">
        <xsl:variable name="int" select="substring-before(IWeight,',')"/>
        <xsl:variable name="dec" select="substring-after(IWeight, ',')"/>
        <xsl:variable name="result" select="number(concat($int,'.',$dec))"/>
        <xsl:variable name="sum" select="$result" />
        <xsl:value-of select="$sum"/>
    </xsl:for-each>
</xsl:template>

看到它在这里工作:https://xsltfiddle.liberty-development.net/ehVZvvD

编辑:

以下是获取每个 Details 节点的 IWeight 总和的方法:

<xsl:template match="/Details">
    <xsl:variable name="weight">
        <xsl:for-each select="Package/Items/IWeight">
            <w>
                <xsl:value-of select="translate(.,',','.')"/>
            </w>
        </xsl:for-each>
    </xsl:variable>
   <xsl:value-of select="sum($weight/w)"/>
</xsl:template>

看到它在这里工作:https://xsltfiddle.liberty-development.net/ehVZvvD/1

基于之前的回答:XSLT 1.0 how to sum values with commas using sum() - walking in xpath