Sanjay
Sanjay

Reputation: 1

How to sum up values inside for-each which has conditional statement in xsl?

Lets say,

I have a quote, where it has multiple quotelines. They differ by LineNumbers(1.1,1.2,2.1,2.2,...). In a configuration(lets say which starts with 1.* or 2.*), I want to sum up all the prices(1.1,1.2,1.3) and put it in a xsl variable. In the same way if there are multiple configurations, I want to do the same thing.(grouping all the config and put the sum of price in to the variables[v1,v2,v3]).

Input XML:

<Quotelines>
 <name>p1</name>
 <lineNo>1.1</lineNo>  
 <amount>100</amount>
 <Qid>1234</Qid>
</Quotelines>
<Quotelines>
 <name>p2</name>
 <lineNo>1.2</lineNo> 
 <amount>1400</amount>
 <Qid>1234</Qid>
</Quotelines> 
<Quotelines>
 <name>p3</name>
 <lineNo>1.4</lineNo> 
 <amount>600</amount>
 <Qid>1234</Qid>
</Quotelines>
<Quotelines>
 <name>p1</name>
 <lineNo>2.1</lineNo>
 <amount>1300</amount>
 <Qid>1234</Qid>
</Quotelines>
<Quotelines>
 <name>p2</name>
 <lineNo>2.2</lineNo>
 <amount>100</amount>
 <Qid>1234</Qid>
</Quotelines> 
<Quotelines>
 <name>p1</name>
 <lineNo>1.1</lineNo>
 <amount>100</amount>
 <Qid>4321</Qid>
</Quotelines>
<Quotelines>
 <name>p2</name>
 <lineNo>1.2</lineNo>
 <amount>100</amount>
 <Qid>4321</Qid>
<Quotelines>

In the above given example, I want to seperate the configurations(1., 2.) of same Qid(1234) and get the sum of amount to be stored in variable1(1.), variable2(2.) etc..,

This is my XSL:

<xsl:template match="/">
<xsl:variable name="tmpTotal">
  <xsl:for-each select="Quotelines>
    <xsl:if test="starts-with(lineNo,'1.')">
      <xsl:value-of select="amount"/>
    </xsl:if>
  </xsl:for-each>
</xsl:variable>
<xsl:variable name="variable1">
  <xsl:value-of select="sum($tmpTotal)"/>
</xsl:variable>

In this XSL, I'm hard coding the lineNo with 1.*. I'm getting the output as(concatinating):

1001400600 

Required Output is:

2100

Upvotes: 0

Views: 1978

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

You do not "sum up values inside for each which has conditional statement". You sum them directly using the sum() function - and you add the condition in a predicate, for example:

<xsl:variable name="variable1" select="sum(Quotelines[starts-with(lineNo, '1.')]/amount)" />

In this XSL, I'm hard coding the lineNo with 1.*.

In order to avoid hard-coding, learn how to group records in XSLT, using either Muenchian grouping (in XSLT 1.0) or xsl:for-each-group (in XSLT 2.0).

Upvotes: 1

Related Questions