Re: adding string-length values

Subject: Re: adding string-length values
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Thu, 23 Nov 2000 09:46:08 +0000

> Well, I'm using Xalan ! But if I understand it right, it should look similar to
> this:
> <xsl:temaple match="Para">
>     <xsl:variable name="mycounter" select="$mycounter_from_parent_node +
>     <xsl:if test="mycounter &lt; 1000">
>         Char count: <xsl:value-of select="$mycounter"/>
>         <xsl:apply-templates select="Para"/>
>     <xsl:if/>
> <xsl:template/>
> Unfortunately I do not know how to obtain the value of $mycounter from the
> parent-node (here: $mycounter_from_parent_node)!!  There are too many
> possibilities (e.g. '../$mycounter') to try them all!  :(

The usual way to do this kind of recursion is to get the total from
'the rest of the Paras' and then add it to the string length of the
'current Para'.  So:

<xsl:template match="Para" mode="get-string-length">
  <xsl:variable name="total_of_rest">
    <!-- get the total from the remaining Paras -->
  <xsl:value-of select="$total_of_rest + string-length(.)" />

In your example, you're dealing with Paras scattered at all levels of
the document tree, so 'the rest of the Paras' are all the Para
elements that either follow this Para or are its descendants.  To get
the list of these Paras, use:

  following::Para | descendant::Para

You can get the total string length of these Para elements by applying
templates to the first one, so you're only interested in the first
Para in that list:

  (following::Para | descendant::Para)[1]

So the Para-matching recursive template looks like:

<xsl:template match="Para" mode="get-string-length">
   <xsl:variable name="total_of_rest">
         select="(following::Para | descendant::Para)[1]"
         mode="get-string-length" />
   <xsl:value-of select="$total_of_rest + string-length(.)" />

In order to kick the process off, you want to apply templates to the
very first Para in the document.  So, in your controlling template,
you need to apply templates to that Para only:

<xsl:template match="Article">
   Total Chars: <xsl:apply-templates select="Para[1]"
                                     mode="get-string-length" />

I've used modes in the above because I think it's likely that you're
going to want to do other things with the Para elements as well as
measure the length of the strings.

I hope that helps,


Jeni Tennison

 XSL-List info and archive:

Current Thread