[xsl] Finding the maximum number of nodes (Redux)

Subject: [xsl] Finding the maximum number of nodes (Redux)
From: "McKeever, Marty" <marty.mckeever@xxxxxxxxxxxxxxxxx>
Date: Wed, 03 Oct 2001 08:17:42 -0400
I hate to resurrect this thread from
http://www.biglist.com/lists/xsl-list/archives/200101/threads.html#00151
but someone on another list asked a very similar question recently, to which
i thought "you should be able to do that with XPath".

The question was "how to determine the number of columns in a table, to
create the correct colspan='x' for a header?"

Boy, did i ever open a can of worms.

After coming up with my own highly convoluted XPath solution, i looked into
the archive for a confirmation and found the thread listed above, which dug
deep into the problem from a template perspective.  I don't know if the
original poster ever got his problem 'solved'.

So here is my XPath solution, submitted for comment.

The XML:

<table>
<tr><td>1.1</td><td>1.2</td></tr>
<tr><td>2.1</td><td>2.2</td><td>2.3</td></tr>
<tr><td>3.1</td></tr>
</table>

The Desired Result:

<table>
<tr><td colspan="3">Table Header Text</td></tr>
<tr><td>1.1</td><td>1.2</td></tr>
<tr><td>2.1</td><td>2.2</td><td>2.3</td></tr>
<tr><td>3.1</td></tr>
</table>

The XSLT:

<xsl:template match="table">
<table border="1"><tr><td>
<xsl:attribute name="colspan"><xsl:value-of select="count(tr[count(td) &gt;
count(following-sibling::tr[count(td) &gt;
count(preceding-sibling::tr[last()]/td)]/td)][count(td) &gt;
count(preceding-sibling::tr[last()]/td)]/td)"/></xsl:attribute>
Table Header Text</td></tr>
<xsl:copy-of select="tr"/>
</table>
</xsl:template>

To paraphrase what (i think!) this XPath means is:

count the number of table cells in the row 
 whose cell count is greater than the
   following sibling row
     whose cell count is greather than it's
       nearest preceding row's cell count
AND
  whose cell count is greater than
    it's own nearest preceding row's cell count.


I know this is highly convoluted, it took me about 2 hours to work out (yes,
i was bored!).  It seems to work correctly in every sample table i can throw
at it (except of course when the td's have thier own colspan attributes --
but that's another question entirely).

Can anyone confirm or deny that this is an acceptable solution?

Marty McKeever

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread