Reputation: 5
I have a situation where I need to loop through one or more funds within a policy record, find the one that has the code TVFIR1 and use that record’s interest rate. This is a super simplified version of the XML record:
<Policy>
<PolicyNumber>123456789</PolicyNumber>
<PolicyOwner>John Doe</PolicyOwner>
<Fund>
<FundCode>TVSPM3</FundCode>
<InterestRate>0</InterestRate>
</Fund>
<Fund>
<FundCode>TVFIR1</FundCode>
<InterestRate>0.025</InterestRate>
</Fund>
<Fund>
<FundCode>TVMDP5</FundCode>
<InterestRate>0</InterestRate>
</Fund>
</Policy>
This is what I am aiming to achieve in pseudocode:
For each fund
If the fund code = ‘TVFIR1 Then
Get its interest rate
Break out of the loop
Else
Interest rate = 0
End If
Next fund record
The logic I would like to use isn’t supported in XSL because you can’t break out of a for-each loop (it's not a procedural language!).
Upvotes: 1
Views: 196
Reputation: 116992
I'd suggest you try it this way:
<xsl:template match="/Policy">
<!-- other stuff -->
<xsl:variable name="fund" select="Fund[FundCode='TVFIR1']" />
<xsl:choose>
<xsl:when test="$fund">
<xsl:value-of select="$fund/InterestRate"/>
</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
<!-- more stuff -->
</xsl:template>
This is assuming you're using XSLT 1.0.
If you are using XSLT 2.0, then you can shorten this to:
<xsl:template match="/Policy">
<!-- other stuff -->
<xsl:variable name="fund" select="Fund[FundCode='TVFIR1']" />
<xsl:value-of select="if ($fund) then $fund/InterestRate else 0"/>
<!-- more stuff -->
</xsl:template>
I would advise you to avoid "clever" tricks that might seem cool at first, but will cost you (or your successor) time later when you try to decipher what exactly they do.
As you have yourself indicated, this is a "if then else" problem and should be solved as such - even if the solution may seem a bit verbose.
Upvotes: 1
Reputation: 8877
Why loop when you can do so in one expression? I believe this XPATH would work for you:
/Policy/Fund[FundCode='TVFIR1']/InterestRate || number(0)
That would select the value of the InterestRate whose FundCode is 'TVFIR1' or the number 0 if it does not exist. Just use that as the value of a variable.
Upvotes: 1