[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

RE: [xsl] how to figure out what level a node is on


Subject: RE: [xsl] how to figure out what level a node is on
From: "Passin, Tom" <tpassin@xxxxxxxxxxxx>
Date: Fri, 14 May 2004 10:53:55 -0400

> From: Morten Andersen [mailto:mortena@xxxxxxxxxx] 
> 
> Thanks. That was exactly what I wanted to do.
> 

However, you may be able to generate your output -which I assume is some
kind of nested menus - without ever knowing the indentation level.  You
would do that by using a recursive template.  That would be possible
with George Bina's example.

If you can manage it, this approach is usually simpler, and better in
the sense that less specific knowledge needs to be coded into the
stylesheet.  But of course how to proceed somewhat depends on what kind
of output you want to get and the form of the input.

To illustrate, here is a simple recursive version to be applied to
George's input data (using xsl:output method='text')-

<xsl:template match='/menu'>
	<xsl:apply-templates select='item'/>
</xsl:template>

<xsl:template match='item'>
	<xsl:value-of select='@name'/> [level <xsl:value-of 
	   select='count(ancestor::item)'/>]
	<xsl:apply-templates select='item'/>
</xsl:template>

Here is the output -

topMenu [level 0]

	subMenu [level 1]

	subSubMenu [level 2]

You would adjust the whitespace in the template to adjust the whitespace
in the output.  The nesting level could also be gotten by passing a
counting parameter in the apply-templates element.  This would eliminate
the need to repeatedly evaluate count(ancestor::item), although this is
unlikely to matter in practice if you are just working with a small
document.

This approach would also easily let you build nested html menus.  For
example, you could output nested div elements to make the menu.  The
flat approach (using //item) would not be a good choice in that case.

Cheers,

Tom P


Current Thread