XSL How to sum elements in different nodes

2019-07-31 23:15发布

I need to sum elements from different nodes. I tried to write different variation of codes but it seems, that I'll missing something important here. Here is my simplified XML file:

<documents>
    <document>
        <rows>
            <row>
                <name>apple</name>
                <amount>10</amount>
            </row>
            <row>
                <name>carrot</name>
                <amount>10</amount>
            </row>
        </rows>
        <client_name>customer_x</client_name>
    </document>
    <document>
        <rows>
            <row>
                <name>banana</name>
                <amount>20</amount>
            </row>
        </rows>
        <client_name>customer_x</client_name>
    </document>
    <document>
        <rows>
            <row>
                <name>banana</name>
                <amount>50</amount>
            </row>
        </rows>
        <client_name>customer y</client_name>
    </document>
</documents>

And here is my current code:

<xsl:for-each select="/documents/document">
    <xsl:if test="contains(client_name, 'customer_x')"> 
        <xsl:value-of select="sum(rows/*/amount)"/>
    </xsl:if>
</xsl:for-each>

Output is: 20 20

But I need output where all these amount values are sum'd together and end result is in this case 40

标签: xml xslt
1条回答
家丑人穷心不美
2楼-- · 2019-07-31 23:38

Let XPath do the work for you:

<xsl:value-of select="sum(/documents/document[client_name='customer_x']//amount)"/>
查看更多
登录 后发表回答