Monday, 5 August 2013

XSLT 2 Find Occurence of each distinct character in a string

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
   
    <!--Two ways two find the occurrence of distnict character in a string-->
   
    <xsl:template match="/">
        <xsl:variable name="value" select="'Vishnu singh shekhawat'"/>
        <xsl:variable name="EachChar">
        <xsl:analyze-string select="." regex="\c">
            <xsl:matching-substring>
                <a><xsl:value-of select="."/></a>
            </xsl:matching-substring>
        </xsl:analyze-string>
        </xsl:variable>
        <xsl:for-each select="distinct-values($EachChar/a)">
            <xsl:sort select="." case-order="lower-first" data-type="text"/>
            <xsl:value-of select="."/> is <xsl:value-of select="count(tokenize($value,.)) - 1"/> <xsl:text> times &#x0A;</xsl:text>   
        </xsl:for-each>
    </xsl:template>
   
   
    <xsl:template match="/">
        <xsl:variable name="value" select="translate('Vishnu singh shekhawat',' ','')"/>
        <xsl:variable name="codePoints" select="string-to-codepoints($value)"/>
        <xsl:variable name="DistnictValue" select="distinct-values($codePoints)"/>
        <xsl:for-each select="$DistnictValue">
            <xsl:value-of select="codepoints-to-string(.)"/> is <xsl:value-of select="string-length($value) - string-length(translate($value,codepoints-to-string(.),''))"/><xsl:value-of select="'&#x0A;'"></xsl:value-of>
        </xsl:for-each>
    </xsl:template>
   
</xsl:stylesheet>