[xsl] Problem selecting following::code

Subject: [xsl] Problem selecting following::code
From: "watchstone@xxxxxxxxxxx" <watchstone@xxxxxxxxxxx>
Date: Mon, 10 Oct 2005 22:22:55 GMT
I am taking a list of items and combining/grouping them by their <id> number (a substring of it) and then outputting each as a separate file.  I asked about creating multiple output files last week and couldn't get the 2.0 solution to work, so I'm using version 1.1 with saxon 6.5.x so please give a solution that will work with that.  Here's the structure of my data:

<root>

<item>
<id>0000-001</id>
<author>Smith, John</author>
<title>ABC</title>
<code>AFCD</code>
</item>

<item>
<id>0000-002</id>
<author>Smith, John</book-author>
<title>123</title>
</item>

<item>
<id>0000-003</id>
<author>Smith, John</book-author>
<title>XYZ</title>
<code>AAAA</code>
</item>

<item>
<id>1234-001</id>
<author>Roberts, Joan</author>
<title>Discover</title>
<code>BCVD</code>
</item>

</root>

Here's an extract of my code:

<xsl:for-each select="//item">

<!-- 
I want to only select the first <item> where
the first four digits of the <id> element match
any number of following <item> elements, so this test
intends to make sure that only the first <item> is selected
-->

<xsl:if test="not(substring(preceding::id[1], 1, 4) = substring(id, 1, 4))">
<author><xsl:value-of select="author"/></author>
<code><xsl:value-of select="code"/></code>

<!--
Now here's where I want to select any other <item> records with the same first four digits of the <id> element that have a <code> element. I tried to use a recursive template but it wasn't selecting the right data.
-->
<xsl:if test="substring(following::id[1], 1, 4) = substring(id, 1, 4)">
<xsl:call-template name="more-codes">
<xsl:with-param  name="c" select="'1'"/>
</xsl:call-template>

<xsl:template name="mode-codes">
<xsl:param name="c"/>
<xsl:if test="substring(following::id[$c], 1, 4) = substring(id, 1, 4)">

<!-- Now here's where I can't figure out how to select only the
<code> element that appears with particular <item> where the <id> elements match.  So in this case, when the id = "0000" I only want to select code = "AAAA" -->

<code><xsl:value-of select="following::code[$c]"/></code>
<xsl:call-template name="more-codes">
<xsl:with-param name="c" select="$c + 1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>

<!-- This of course selects the <code> element for the wrong record (with id="1234") because some of the records where the <id> matches don't have <code> elements. 
 -->
Thanks for your assistance.

Current Thread