Re: [xsl] backwards tree-traversal algorithm?

Subject: Re: [xsl] backwards tree-traversal algorithm?
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Wed, 23 Oct 2002 15:38:45 +0100
Hi John,

> hello, having some trouble making this work: within my stylesheet, i
> have selected a node somewhere in the midst of the document tree,
> several nested elements deep. what i would like to do is, given this
> node N (at arbitrary depth), walk *back* up the document tree
> hierarchy, element by element, printing the successive parent
> elements (technically, printing each element's "name" @ribute).

The easiest way to do this is to collect the ancestor elements using
the ancestor attribute and iterate over them sorted in reverse
document order:

  <xsl:for-each select="ancestor::*">
    <xsl:sort select="position()" order="descending"
              data-type="number" />
    <xsl:value-of select="@name" />
    <xsl:if test="position() != last()">, </xsl:if>
  </xsl:for-each>

[Note that I've done what you said (use the 'name' attribute) rather
than what you showed in your examples (which used the name of the
element).]

But you can do it using recursion instead if you want:

<xsl:template match="*" mode="name">
  <xsl:if test="parent::*">
    <xsl:apply-templates select="parent::*" mode="name" />
    <xsl:text>, </xsl:text>
  </xsl:if>
  <xsl:value-of select="@name" />
</xsl:template>

Cheers,

Jeni

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


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


Current Thread