Reputation: 13
For example if you have a string that does not have a fixed length, but is always in increments of 2, how should I break up the string into multiple parts and call a template for each of the substring, as each of them correspond to a different text.
<root>
<Data>
<ErrorNumber>12345678</ErrorNumber>
</Data>
</root>
For the error codes suppose
12 = "Test 1"
34 = "Test 2"
56 = "Test 3"
78 = "Test4"
So that function should call this function and get the output
<xsl:template name="GetErrorCode">
<xsl: param name = "ErrorCode"/>
<xsl: if test = "$ErrorCode = '12'">
<xsl:text> Test 1 </xsl:test>
</xsl:if>
</xsl template>
So basically if I pass 12345678 as param I would get
Test 1
Test 2
Test 3
Test 4
As Output
Upvotes: 1
Views: 3157
Reputation: 23637
You could use XPath substring to extract the fixed blocks and assign them to XSLT variables:
<xsl:variable name="A" select="substring(/root/Data/ErrorNumber, 1, 2)"/>
<xsl:variable name="B" select="substring(/root/Data/ErrorNumber, 3, 2)"/>
<xsl:variable name="C" select="substring(/root/Data/ErrorNumber, 5, 2)"/>
<xsl:variable name="D" select="substring(/root/Data/ErrorNumber, 7, 2)"/>
And from there use the variables in your test.
The template below can be used if the size of the codes are not of fixed length:
<xsl:template name="tokenize">
<xsl:param name="text"/>
<xsl:choose>
<xsl:when test="string-length($text) = 2">
<token><xsl:value-of select="$text"/></token>
</xsl:when>
<xsl:otherwise>
<token><xsl:value-of select="substring($text, 1, 2)"/></token>
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="substring($text, 3, string-length($text)-2)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
It will return a node-set containing one or more elements, for example, if you call it with:
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="/root/Data/ErrorNumber" />
</xsl:call-template>
Where ErrorNumber is 12345678, you get a variable $tokens
containing:
<token>12</token>
<token>34</token>
<token>56</token>
<token>78</token>
Then you can call your template passing $tokens/token[2]
to obtain the desired result.
Upvotes: 2