Re: [xsl] Summing Time Durations Help

Subject: Re: [xsl] Summing Time Durations Help
From: Colin Paul Adams <colin@xxxxxxxxxxxxxxxxxx>
Date: 05 Oct 2005 08:26:22 +0100
>>>>> "Kent" == Kent Seegmiller <hookjaw20@xxxxxxxxxxx> writes:

    Kent> I have some duration elements like <alltimes>
    Kent> <tduration>PT1H23M</tduration> <tduration>PT5M</tduration>
    Kent> <tduration>PT44M12S</tduration>
    Kent> <tduration>PT57M23S</tduration> ...  </alltimes>

    Kent> What is the most efficient way to sum the durations?  Is
    Kent> there an xpath = expression for this?

Yes. If you are using XPath 2.0.
You should use the sum() function.
But first you need some duration values - at present, all you have are
string literals - untyped text nodes.
So if you have a prefix, say xdt, bound to the XPath dataypes namespace,
you can convert the text node to a dayTimeDuration with the expression:

xdt:dayTimeDuration(text())

if the context node is a tduration.

So:

 sum (tduration/xdt:dayTimeDuration (text()))

looks suitable.

The following stylesheet (tested with gexslt):

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0"
   xmlns:xdt="http://www.w3.org/2005/xpath-datatypes";>

  <xsl:output method="text" />

  <xsl:template match="/alltimes">
    <xsl:value-of select="sum (tduration/xdt:dayTimeDuration (text()))" />
  </xsl:template>

</xsl:transform>

produces the result:

PT3H9M35S

which is the correct result according to my mental arithmetic.

With Saxon 8.5.1 I get the error:

Error at xsl:value-of on line 7 of file:/home/colin/test.xsl:
  XPST0003: XPath syntax error at char 43 on line 7 in {.../xdt:dayTimeDuration (text(...}:
    Cannot find a matching 1-argument function named
  {http://www.w3.org/2005/xpath-datatypes}dayTimeDuration()
Failed to compile stylesheet. 1 error detected.

I guess this means that Saxon 8.5.1 does not use the latest namespace,
so you would have to edit the xmlns line accordingly.

-- 
Colin Adams
Preston Lancashire

Current Thread