我们有一个带有Invoices / Invoice / [asst]的xml文档。元素],使用xslt调用模板,我们需要对InvoiceAmounts求和以匹配InvoiceNumbers。
输入xml文件:
<Invoices>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>137.50</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>362.50</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351511</InvoiceNumber>
<InvoiceAmount>239.50</InvoiceAmount>
</Invoice>
</Invoices>
我找到了一条选择语句,该语句返回整个文档的InvoiceAmounts的总和,但是需要根据InvoiceNumber将其过滤为一个总和,因为在Invoices文档中可能有多个具有相同InvoiceNumber的发票。
返回总和:
<xsl:value-of select="sum(/*[local-name()='Invoices']/*[local-name()='Invoice']/*[local-name()='InvoiceAmount'])" />
根据我的研究,下面的此查询应将结果过滤到一个InvoiceNumber,但不是。因此,我们在此模板p1中添加了一个参数,并格式化了下面的查询。还有另一种格式化此选择格式的方法,以便仅针对那些InvoiceNumbers = $ p1来获取总计吗?尝试了多种变体,仍然无法获得预期的结果。有没有一种方法可以将$ p1变量添加到select中以过滤结果?
<xsl:value-of select="sum(/*[local-name()='Invoices']/*[local-name()='Invoice'][local-name()='InvoiceAmount' = $p1]/*[local-name()='InvoiceAmount'])" />
预期成绩:
<Invoices>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>500.00</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>500.00</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351511</InvoiceNumber>
<InvoiceAmount>239.50</InvoiceAmount>
</Invoice>
</Invoices>
谢谢您的考虑。
汤姆
最佳答案
此样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="InvoiceAmount">
<InvoiceAmount>
<xsl:value-of
select="sum(../../Invoice[InvoiceNumber=
current()/parent::*/InvoiceNumber]/InvoiceAmount)"/>
</InvoiceAmount>
</xsl:template>
</xsl:stylesheet>
产生:
<Invoices>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>500</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351510</InvoiceNumber>
<InvoiceAmount>500</InvoiceAmount>
</Invoice>
<Invoice>
<InvoiceNumber>351511</InvoiceNumber>
<InvoiceAmount>239.5</InvoiceAmount>
</Invoice>
</Invoices>
注意:格式化钱是一种练习。请参见
xsl:decimal-format
。