Re: [xsl] The identity transform and attributes

Subject: Re: [xsl] The identity transform and attributes
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Mon, 21 Jan 2008 16:22:50 +0000
On 21/01/2008, Jesper Tverskov <jesper@xxxxxxxxxxx> wrote:
> The old way even has the power and fascination of being just one
> template, the identity template. This is how the identity template
> looks in two specs, in hundreds of books, in thousands of articles and
> tutorials, and in millions of XSLT stylesheets until this very day.
>
> Why change things for the worse just to confuse people?

Well the standard identity template is completely non-intuitive in
itself... so I think most new XSLT'ers are confused enough by it.  I
remember in the early days cutting and pasting it the first few times
I needed it just because it seemed so strange and hard to reproduce by
hand.  Having something within xsl:copy was the hardest thing to
comprehend, iirc.

Anyway, this thread was about understanding a little better how the
identity template processes attributes.

For example, try this with Saxon:

<xsl:template match="@*">
   <xsl:copy>
       <xsl:apply-templates select="@*|node()"/>
   </xsl:copy>
</xsl:template>

You get the warning:

"The child axis starting at an attribute node will never select anything"

The apply-templates call is effectively redundant for some of the
node() kinds... so why leave it in?  From a human perspective it's
nice and compact, but from a processing perspective it's odd.  Compact
code is a hackers dream and a maintainers nightmare, so its not
something to necessarily aspire to.

A less compact but possibly more intuitive indentity transform is the
one Mike suggested right at the beginning:

<xsl:template match="element()">
   <xsl:copy>
       <xsl:apply-templates select="@*,node()"/>
   </xsl:copy>
</xsl:template>

<xsl:template match="attribute()|text()|comment()|processing-instruction()">
   <xsl:copy/>
</xsl:template>

Had that been the one that I learnt, I might have realised sooner that
attributes don't have children (and I might have understood the whole
thing a little quicker).

As the original identity template is ingrained in my mind though I'll
continue to use that - along with the "@*, node()" modification.


-- 
Andrew Welch
http://andrewjwelch.com
Kernow: http://kernowforsaxon.sf.net/

Current Thread