Page 1 of 1

Counting examples

Posted: Wed Mar 24, 2010 7:21 pm
by ra0543
Is there a straightforward way function to count the number of times a particular character or sequence of characters appears in the text of an element? For instance in

Code: Select all

<a>This (i.e. <b>an example</b>) is an example.</a>
I would like to be able to count how many times the letter 'i' appears in element <a> (which is, of course, 3 times), whether there are the same number of '(' characters as ')' in <a>, and the like.

Re: Counting examples

Posted: Thu Mar 25, 2010 12:04 pm
by george
Hi,

For checking characters you can use the translate function to remove a character from the text and then you can look at the length of the text before and after that, for example:

Code: Select all


<xsl:template match="a">
<xsl:value-of select="string-length(.) - string-length(translate(., 'i', ''))"/>
</xsl:template>
If you want to check a sequence of characters then it gets difficult with XSLT/XPath 1.0 but it should be easy with XSLT/XPath 2.0 where you have a number of regexp functions like matches, replace or tokenize.

Best Regards,
George

Re: Counting examples

Posted: Thu Mar 25, 2010 7:48 pm
by ra0543
Thanks, that will do what I have in mind.

Can I modify this so that the contents of <b> are ignored when processing <a>?
In other words, if I have

Code: Select all

<a>This (i.e. <b>an example)</b> is an example.</a>
I'd like the test here to come out false:

Code: Select all

<xsl:template match="a">
<xsl:if test="string-length(translate(.,'(',''))!=string-length(translate(.,')',''))"> ... </xsl:if>
</xsl:template>
differently from when I test this:

Code: Select all

<a>This (i.e. <b>an example</b>) is an example.</a>

Re: Counting examples

Posted: Fri Mar 26, 2010 6:31 pm
by george
You can select only the text nodes from the element "a" with something like

Code: Select all


<xsl:variable name="aText">
<xsl:value-of select="text()" separator="''"/>
</xsl:variable>
then use this variable instead of "." in the following expression.

Best Regards,
George