Re: [xsl] Conditional Selection of Nodes

Subject: Re: [xsl] Conditional Selection of Nodes
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Thu, 10 May 2001 09:37:18 +0100
Hi Ciaran,

> I have the following XML ...
>
> <foo>
>    <b>content</b>
>    <b>more content</b>
>    <p>yet more content</p>
>    <i>some more conent</i>
> </foo>
>
> and what I want is to put all child elements of 'foo' that are not
> in 'p' elements into a 'p' element, in order.

The easiest way is to step through the child nodes of foo one by one
and decide what to do with them as you go.  Apply templates only to
the first child:

<xsl:template match="foo">
   <xsl:apply-templates select="*[1]" />
</xsl:template>

If the element is a p element, you want to copy it and move on to the
next sibling:

<xsl:template match="p">
   <xsl:copy-of select="." />
   <xsl:apply-templates select="following-sibling::*[1]" />
</xsl:template>

Otherwise, you want to create a p element.  Within it, apply templates
to the same node but in a different mode ('wrapped' or something).
Then apply templates to the next p element:

<xsl:template match="*">
   <p>
      <xsl:apply-templates select="." mode="wrapped" />
   </p>
   <xsl:apply-templates select="following-sibling::p[1]" />
</xsl:template>

In wrapped mode, you want to copy the current node and then move on to
its next sibling, but only if that sibling isn't a p element:

<xsl:template match="*" mode="wrapped">
   <xsl:copy-of select="." />
   <xsl:apply-templates select="following-sibling::*[1][not(self::p)]"
                        mode="wrapped" />
</xsl:template>

I hope that helps,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/



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


Current Thread