RE: [xsl] Using the Input Document to Control Generation of Numbers in the Output

Subject: RE: [xsl] Using the Input Document to Control Generation of Numbers in the Output
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Tue, 2 Oct 2007 13:36:59 +0100
> 2.
> Count with specification of sizes.
> In this case the nodes in the incoming document may include 
> an attribute to indicate that they need to allocate more than 
> one number.
>  
> <incoming name="a" />
> <incoming name="b" size="4" />
> <incoming name="c" />
> <incoming name="d" size="2" />
> <incoming name="e" />
>  
> <outgoing name="a" index="1" />
> <outgoing name="b" index="2" />
> <outgoing name="c" index="6" />
> <outgoing name="d" index="7" />
> <outgoing name="e" index="9" />

This is a typical use case for recursion (even in XSLT 2.0). 

<xsl:template match="incoming">
  <xsl:param name="total-so-far"/>
  <xsl:variable name="new-total" select="$total-so-far + (@size, 1)[1]"/>;
  <outgoing name="{@name}" index="{$new-total}"/>
  <xsl:apply-templates select="following-sibling::incoming[1]">
    <xsl:with-param name="total-so-far" select="$new-total"/>
  </xsl:apply-templates>
</xsl:template>

and then fire the process off with

<xsl:template match="parent-of-incoming">
  <xsl:apply-templates select="incoming[1]">
    <xsl:with-param name="total-so-far" select="0"/>
  </xsl:apply-templates> 
</xsl:template>  

Problem 3 is a trivial variation.

I tend to find when teaching that this is an area many students have trouble
with. You show them an example, and they seem to understand it; then you ask
them to do one and they get tied in knots. But it's not that difficult once
you've grasped it.

Michael Kay
http://www.saxonica.com/

Current Thread