Jyotish Singh
Jyotish Singh

Reputation: 2115

Count number of character in a variable in XSLT 2.0

I have an XML which is describe below. This xml contains for example address node(address1). I just want to count the number of occurrence of character(,) in the address text. I am using template so just to mention I an storing address text into xslt variable.

Sample XML:

<xml>
    <address1>123 Fake Street, Alberta, Alberta, 234567</address1> 
    <address1>123 Fake Street, Alberta, Alberta</address1>
</xml> 

My XSLT:

<xsl:variable name="address" select="//*[local-name()='address1')]"/>
<xsl:variable name="totalComma" select="count(contains($address, ','))"/>
<xsl:choose>
<xsl:when test="$totalComma = 3">
    <!--Do something-->
</xsl:when>
<xsl:when test="$totalComma = 2">
    <!--Do something-->
</xsl:when>
</xsl:choose>

I don't know whether this is correct solution or not but didn't get expected result. A little help would be highly appreciable.

Upvotes: 6

Views: 6408

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167436

Use string-length(foo) - string-length(translate(foo, ',', '')).

Upvotes: 11

Related Questions