[xsl] counting element characters

Subject: [xsl] counting element characters
From: tom s <tshmit@xxxxxxxxx>
Date: Sun, 10 Aug 2008 15:17:48 -0700 (PDT)
I'm almost as embarrassed by this question as I am baffled by it....I'd like to sum the number of PCDATA characters contained in specified elements. For example:

<doc>
<a>
    <p>some text to be counted</p> <!-- 23 chars there -->
    <x>other text</x>
    <p>some more text to be counted</p> <!-- 28 chars -->
</a>
</doc>

I'd like to calculate the sum of characters in the <p> tags; here 51.

I thought I would use something like:
<xsl:template match="a">
    <xsl:variable name="c">
            <xsl:for-each select="descendant::p">
               <xsl:value-of  select="string-length(.)"/>
            </xsl:for-each>
    </xsl:variable>
    <xsl:value-of select="sum($c/text())"/>
</xsl:template>

This seems to work in the xmlspy processor, but saxon generates values like 3.0010118811741284E51, which is substantially more than the number of atoms in the universe, I think. I assume it is some sort of type problem...

Also, if it happens that <a> contains no <p> elements, saxon complains that it can't convert an empty string to a double. I tried conditioning the evaluation of the sum() on <xsl:when test="count($c/text()) > 0">, to avail.

Any help is greatly appreciated!!

Current Thread