Re: [xsl] is there a more concise way of pulling diverse elements into a for-each?

Subject: Re: [xsl] is there a more concise way of pulling diverse elements into a for-each?
From: "Michael Kay michaelkay90@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Wed, 27 Mar 2024 08:05:44 -0000
Template rules are your friend: replace the call on xsl:for-each with a call
on xsl:apply-templates, perhaps with a named mode, and then write template
rules for matching the indvidual elements. You might use one rule for each
element:

<xsl:template match="document">...</xsl:template>

or one rule that matches several elements:

<xsl:template match="document|section">....

or you might make it the default rules

<xsl:template match="*">....

with specific rules for the elements that you DON'T want to match.

For the `included` element, write a rule that recurses:

<xsl:template match="included">
   <xsl:apply-templates select="document | section | heading"/>
</xsl:template>

Michael Kay
Saxonica

> On 27 Mar 2024, at 06:47, Trevor Nicholls trevor@xxxxxxxxxxxxxxxxxx
<xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx> wrote:
>
> Hi
>
> Application is using XSL 2.0
>
> Apologies if this is a standard pattern or a FAQ
>
> I have this issue in several places but the most obvious is where I am
generating a TOC for a large document, and I need to extend it to pull in a
few additional elements
>
> The stylesheet started with a template which uses this kind of
construction:
>
>    <xsl:for-each select="document | included/document | section |
included/section | heading | included/heading">
>    b&
>    </xsl:for-each>
>
> This is OK but it doesn't scale well, and now I need to add half a dozen
additional elements to the selection, e.g.
>
>    <xsl:for-each select="document | included/document | section |
included/section | heading | included/heading | function | included/function |
switch | included/switch | b&">
>    b&
>    </xsl:for-each>
>
> The pattern is rapidly getting out of hand (aka error-prone) and I wonder if
there is a better way of handling this construction, without requiring a
schema change.
>
> As it happens all the elements listed above have an id attribute, so I
tried
>
>    <xsl:for-each select="*[@id] | included/*[@id]">
>
> but that selects far too much; there are numerous elements with ids which I
do not want to select, and a list of items to exclude would be as long or
longer than the list which I need to include.
>
> XSL is so elegant there must be a better way, but I haven't been able to
come up with it on my own. Can someone point me in the right direction
please?
>
> cheers
> T
>
>
> XSL-List info and archive <http://www.mulberrytech.com/xsl/xsl-list>
> EasyUnsubscribe <http://lists.mulberrytech.com/unsub/xsl-list/3500899> (by
email <>)

Current Thread