XSLT基于两个不同表中的数据的值之和
XML:XSLT基于两个不同表中的数据的值之和,xslt,Xslt,XML: 1. 1000 2. 2000 3. 3000 1. 100 2. 100 我在表中显示金额,但仅当表2中存在“拆分”值时 <Budget> <Table1> <AllocID>1</AllocID> <Amount>1000</Amount> </Table1> <Table1> <AllocID>2&
1.
1000
2.
2000
3.
3000
1.
100
2.
100
我在表中显示金额,但仅当表2中存在“拆分”值时
<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>
//这里记录的总数。
我需要从表1中获得金额的总和,但前提是表2中存在AllocID的值。所以在这个例子中,我只想要AllocIDs 1和2的金额之和。在xslt中如何做到这一点而不修改给定的数据集 对于您的输入数据一无所知(我不知道您为什么选择不使用实际的XML),我不得不猜测一下:
<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.
也可以使用递归函数计算运行总和,如下所示:
<!-- this will return 3000 for the above input -->
<xsl:template match="/" >
<xsl:value-of select="
sum(Budget/Table1/AllocID[. = //Budget/Table2/AllocID])
" />
</xsl:template>
这是较慢的,但在计算过程中允许更大的灵活性。例如,可以将所有非数值替换为0。或者根据您自己的规则使用给定节点的不同值。谢谢您的建议。我可以使用第一个,只需稍加修改:sum(Budget/Table1[./AllocID=//Budget/Table2/AllocID]/Amount)。我还用xml更新了这个问题,以供将来的读者参考。我必须添加的一件事是检查零,如下@Andez:很高兴看到我的一个旧答案今天仍然对某人有帮助。谢谢你的反馈!(我的回答中包含了一个修正)
<!-- 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() > 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>