Re: [xsl] Choosing based on current node

Subject: Re: [xsl] Choosing based on current node
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Mon, 12 Feb 2007 17:29:18 +0100
sthomas2@xxxxxxx wrote:
I'm amazed at how patient this list is with newbie questions; I hope
this question doesn't try that patience too much. I'm processing a
document that has <A> or <B> or <C> elements in it. I need to preserve
their order in the output, but do something drastically different for
each. It seems like the following ought to work, but, instead, the
otherwise branch is always performed, regardless of whether the element
is A, B, or C. (The for-each is working fine, as it correctly skips over
any elements other than A, B, or C.)

<xsl:for-each select="A|B|C">
<xsl:choose>
<xsl:when test=".=A">

Hi Stephen,


Your test only needs to read
test="A"

for A, etc. This will test for a node whose name is A (better: whose qualified name matches the qualified name A)

However, I think you are much better off doing this through matching templates. Try this instead (place them anywhere directly under the xsl:stylesheet element):

<xsl:template match="A">
     place the bits here that you have now in template-name='do-A'
</xsl:template>

<xsl:template match="A">
     place the bits here that you have now in template-name='do-B'
</xsl:template>
....

Now, in your main entry point (initial template), where you currently have put the for-each loop, you should replace the for-each loop with:

<xsl:apply-templates select="A|B|C" />

This will tell the processor to search for the template matches in your document. The input document order will be retained, so no worries about that (for-each or apply-templates neither influence the way the document is being processed, which is in document order).

Your approach much resembles the way the GOTO approach took over the world back in 1967. However, OO has largely replaced GOTO (which by many is now considered evil) as you should replace as many call-templates with template matches if possible (the XSLT way of structuring your stylesheet and making them easier to maintain).

Cheers,
-- Abel Braaksma
  http://xslt.metacarpus.com

Current Thread