XPath中求和和乘积的聚合函数 [英] Aggregate-function for sum and product in XPath
问题描述
类似于这个问题(http://stackoverflow.com/q/1333558/948404),我想使用XPath来计算如下结构的乘积之和:
Similar to this question (http://stackoverflow.com/q/1333558/948404) I want to use XPath to calculate a sum over products in a structure like this:
<items>
<item>
<value>1.0</value>
<quantity>3</quantity>
</item>
<item>
<value>2.5</value>
<quantity>2</quantity>
</item>
<!-- ... -->
</items>
是否存在一个XPath表达式来计算每个项目value
和quantity
的乘积之和?
Is there an XPath expression that calculates the sum of the products of each items value
and quantity
?
更新:该解决方案必须与PHP的XSLTProcessor类一起使用,这意味着它可能必须与XSLT 1.0兼容.这就是为什么我尚未使用XSLT 2.0接受两个可能正确的答案的原因.我既无法在PHP实现中,也无法在浏览器中,也无法在w3schools的Tryit Editor [1]中对其进行测试.抱歉!
Update: The solution has to work with PHPs XSLTProcessor class meaning that it probably has to be XSLT 1.0 compliant. This is why I did not yet accept the two probably correct answers using XSLT 2.0. I could neither test them in my PHP implementation nor in my browser nor in the Tryit Editor [1] from w3schools. Sorry!
推荐答案
使用此XPath 2.0表达式:
sum(/items/item/(value * quantity))
以下是XSLT 2.0转换作为验证:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:sequence select="sum(/items/item/(value * quantity))"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的XML文档时:
<items>
<item>
<value>1.0</value>
<quantity>3</quantity>
</item>
<item>
<value>2.5</value>
<quantity>2</quantity>
</item>
<!-- ... -->
</items>
将评估XPath表达式并输出该评估的结果:
8
说明:
在XPath 2.0中,将位置步骤设为
In XPath 2.0 it is legal for a location step to be
/(expression)
,
甚至
/someFunction(argumentList)
II. XSLT 1.0解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<xsl:call-template name="sumProducts">
<xsl:with-param name="pNodes" select="item"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="sumProducts">
<xsl:param name="pNodes" select="/.."/>
<xsl:param name="pAccum" select="0"/>
<xsl:choose>
<xsl:when test="not($pNodes)">
<xsl:value-of select="$pAccum"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sumProducts">
<xsl:with-param name="pNodes" select="$pNodes[position() >1]"/>
<xsl:with-param name="pAccum" select=
"$pAccum + $pNodes[1]/value * $pNodes[1]/quantity"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
将此转换应用于提供的XML文档时(上面),再次产生所需的正确结果:
8
注意:使用 FXSL库 .调用的模板是transform-and-sum
.
这篇关于XPath中求和和乘积的聚合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!