Counting examples

Here should go questions about transforming XML with XSLT and FOP.
ra0543
Posts: 80
Joined: Wed Jan 14, 2009 12:50 pm

Counting examples

Post 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.
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Re: Counting examples

Post 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
George Cristian Bina
ra0543
Posts: 80
Joined: Wed Jan 14, 2009 12:50 pm

Re: Counting examples

Post 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>
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Re: Counting examples

Post 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
George Cristian Bina
Post Reply