Wednesday, February 4, 2009

String starts with a number in XSL

I needed a way to test if a particular value in an XML file started with a letter based prefix. If not, then the value would start with a number and needed to be prefixed first before being output. While I found a great post how to remove leading zeros I could not find how to check if the first letter is of a particular type, for example a letter or a number. In Java you can do that easily like so (using BeanShell here):

bsh % String s1 = "1234";
bsh % String s2 = "A1234";
bsh % print(Character.isLetter(s1.charAt(0)));
bsh % print(Character.isLetter(s2.charAt(0)));

This is of course Unicode safe. With XSL though I could not find a similar feature but for my purposes it was sufficient to reverse the check and see if I had a Latin number first. Here is how:
<xsl:template match="/person/personnumber">
<xsl:variable name="num">
<xsl:value-of select="."/>
<xsl:when test="contains('0123456789', substring($num, 1, 1))">
<xsl:variable name="snum">
<xsl:call-template name="removeLeadingZeros">
<xsl:with-param name="originalString" select="$num"/>
<xsl:value-of select="concat('PE', $snum)"/>
<xsl:value-of select="."/>

No comments:

Post a Comment