RE: [xsl] Porting own template language to xslt

Subject: RE: [xsl] Porting own template language to xslt
From: "Nick Fitzsimons" <nick@xxxxxxxxxxxxxx>
Date: Thu, 16 Mar 2006 12:36:31 -0000 (GMT)
> On Thu, 2006-03-16 at 11:16 +0000, Michael Kay wrote:
>> I think that using xsl:for-each is the natural way to do this.
>
> Interestingly I just had a Prof of CS call me for help (he's learning
> XSLT) and he thought it was completely unnatural -- semantically --
> to use for-each just to switch contexts for a single node; that it
> should be kept for iteration over 1+ nodes.
>

I would have expected a Prof of CS to realise that XSLT doesn't do
iteration. The XSLT 1.0 standard states:

"The xsl:for-each instruction contains a template, which is instantiated
for each node selected by the expression specified by the select
attribute. The select attribute is required. The expression must evaluate
to a node-set."
<http://www.w3.org/TR/xslt#for-each>

As it is perfectly acceptable for a set to have 0, 1 or more members,
there's no reason xsl:for-each shouldn't be used to instantiate a template
even when it is known in advance that the node-set will have only one
member. I get the impression that this Prof is attributing a semantic
value to xsl:for-each which is not present, and makes no sense, in a
declarative language.

It appears that the Prof is thinking in terms of

for (int i = 0; i < 1; i++) {
   /* do stuff only once */
}

which is clearly a waste of time; but in XSLT, using

<xsl:for-each select="element[1]">
  <!-- do stuff to only one thing -->
</xsl:for-each>

is perfectly reasonable.

A lot of people fall into the trap of applying procedural concepts to
XSLT, so he's not alone; but thinking of xsl:for-each as somehow iterating
in the same way as a "for" construct in a C-type language can only lead to
misery. It's the reason so many people write to this group asking "How can
I break out of this loop" and are often confused by the
Matrix-paraphrasing response, "There is no loop."

Regards,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/

Current Thread