Re: [xsl] Variable containing tree

Subject: Re: [xsl] Variable containing tree
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Fri, 7 Jun 2002 10:45:04 +0100
Hi Filipe,

> I'm assigning a set of nodes to a variable like this:
>
>       <xsl:variable name="var">
>          <xsl:apply-templates/>
>       </xsl:variable>
>
> wich I would like to output later on only if the variable is not empty.

What do you mean by "empty"? The variable $var is being set to a
result tree fragment -- a little node tree on which you can only (in
unextended XSLT 1.0) perform string operations. If the
xsl:apply-templates instruction doesn't generate any content, then the
result tree fragment only has a root node, so doing:

  <xsl:if test="$var != ''">
     ... not empty ...
  </xsl:if>

will let you know whether that happens. Unfortunately, though, the
$var result tree fragment, when converted to a string, is also empty
if the elements that you create within it don't themselves have any
content. So for example if you did:

  <xsl:variable name="var">
    <br />
  </xsl:variable>

then $var = '' would also be true because the string value of the root
node of the result tree fragment (the concatenation of all the text
node descendants of the RTF) is empty.

If you want to test whether the result tree fragment's root node has
any children (i.e. the xsl:apply-templates created anything), then you
have to convert the result tree fragment to a node set, using an
extension function as you've discovered, and then test that:

  <xsl:variable name="var-rtf">
    <xsl:apply-templates />
  </xsl:variable>
  <xsl:variable name="var" select="xalan:nodeset($var-rtf)" />
  <xsl:if test="$var/node()">
    <result>
      <xsl:apply-templates select="$var/node()" />
    </result>
  </xsl:if>

Note that $var/node() gives you a node set of the nodes under the
result tree fragment's root node; it appears as if these are the nodes
to which you wish to apply templates.  (If you just want to copy the
result, then use xsl:copy-of.)
  
Cheers,

Jeni

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


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


Current Thread