代码之家  ›  专栏  ›  技术社区  ›  tessa

基于两个不同表中数据的XSLT值总和

  •  0
  • tessa  · 技术社区  · 16 年前

    <Budget>
        <Table1>
            <AllocID>1</AllocID>
            <Amount>1000</Amount>
        </Table1>
        <Table1>
            <AllocID>2</AllocID>
            <Amount>2000</Amount>
        </Table1>
        <Table1>
            <AllocID>3</AllocID>
            <Amount>3000</Amount>
        </Table1>
        <Table2>
            <AllocID>1</AllocID>
            <Split>100</Split>
        </Table2>
        <Table2>
            <AllocID>2</AllocID>
            <Split>100</Split>
        </Table2>
    </Budget>
    

    <xsl:for-each select="Budget/Table1">
        <xsl:for-each select="//Budget/Table2[AllocID = current()/AllocID]">
            <xsl:value-of select="Amount"/>
        </xsl:for-each>
    </xsl:for-each>
    //Total for the records here.
    

    1 回复  |  直到 16 年前
        1
  •  2
  •   Tomalak    15 年前

    对输入数据一无所知(我不知道你为什么选择

    <Budget>
      <Table1>
        <AllocID>1000</AllocID>
        <AllocID>2000</AllocID>
        <AllocID>3000</AllocID>
      </Table1>
      <Table2>
        <AllocID>1000</AllocID>
        <AllocID>2000</AllocID>
      </Table2>
    </Budget>
    

    XPath sum() function 以及正确的XPath表达式:

    <!-- this will return 3000 for the above input -->
    <xsl:template match="/" >
      <xsl:value-of select="
        sum(Budget/Table1/AllocID[. = //Budget/Table2/AllocID])
      " />
    </xsl:template>
    

    运行和也可以用递归函数计算,如下所示:

    <!-- this will also return 3000 for the above input -->
    <xsl:template match="/" >
      <xsl:call-template name="total">
        <xsl:with-param name="nodes" select="
          Budget/Table1/AllocID[. = //Budget/Table2/AllocID]
        " />
      </xsl:call-template>
    </xsl:template>
    
    <xsl:template name="total">
      <xsl:param name="nodes" />
    
      <xsl:choose>
        <!-- either there is something to calculate... -->
        <xsl:when test="string(number($nodes[1])) != 'NaN'">
          <xsl:variable name="subtotal">
            <xsl:call-template name="total">
              <xsl:with-param name="nodes" select="$nodes[position() &gt; 1]" />
            </xsl:call-template>
          </xsl:variable>
          <xsl:value-of select="number($nodes[1]) + $subtotal" /> 
        </xsl:when>
        <!-- ...or we assume 0 -->
        <xsl:otherwise>
          <xsl:value-of select="0" /> 
        </xsl:otherwise>
      </xsl:choose>
    
    </xsl:template>