Jack Wong
Jack Wong

Reputation: 33

XSL How to sum the node value based on condition

XML FILE

<?xml version="1.0"?>

<books>
<book>
    <title fiction="true">Happy Potter</title>
    <author>J. K. Rowling et al</author>
    <price>29.99</price>
</book>

<book>
    <title fiction="true">The Hobbit</title>
    <author>J.R.R. Tolkien</author>
    <price>25.99</price>
</book>

<book>
    <title fiction="true">Greater than 30</title>
    <author>J.R.R. Tolkien</author>
    <price>31.99</price>
</book>

<book>
    <title fiction="false">Non-Fiction</title>
    <author>J.R.R. Tolkien</author>
    <price>19.99</price>
</book>

XSL FILE

<xsl:for-each select="books/book">
<xsl:if test="(title[@fiction='false']) and (price &lt; 30)">
<span name="title"><xsl:value-of select="title"/></span><br/>
<span name="author"><xsl:value-of select="author"/></span><br/>
<span name="price"><xsl:value-of select="price"/></span><br/><br/>
</xsl:if>
</xsl:for-each>   

Total: <span name="total"><xsl:value-of select="sum(books/book/price)"/></span>

So my XSL will extract the data from XML based on the condition given. When the fiction=true and the price is < 30. But I have no idea how to sum the total value. Any advise will be appreciate.

Upvotes: 0

Views: 1725

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use a predicate sum(books/book[title[@fiction='false'] and price &lt; 30]/price).

Also you can shorten

<xsl:for-each select="books/book">
<xsl:if test="(title[@fiction='false']) and (price &lt; 30)">

to

<xsl:for-each select="books/book[title[@fiction='false'] and price &lt; 30]">

Upvotes: 2

Related Questions