This is the mail archive of the xsl-list@mulberrytech.com mailing list .


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: use variable in <xsl:if test=


On Saturday 02 March 2002 00:52, Robert Sösemann wrote:
> Instead of writing
>
> <xsl:if test="*//author='C. J. Date']"/>
>
> 10 times in my stylesheet I want to use ONE variable or constant
> to set it once at the beginning and then use it like that:
>
> <xsl:if test=variable/>
>
> How must I declare this variable and how do I use it in xsl:if?

The problem is that when the variable is set, your expression is only 
evaluated once.  So if you have <xsl:if test="$condition"> elsewhere in your 
document, they will *all* have the same result; the *[//author='...'] is not 
evaulated for each context-node, it is evauluated only once with the document 
root as the context.  This means that if there are any <author>C. J. 
Date</author> tags anywhere in your document, then all of the <if>'s will be 
true.

There are two ways to have the expression be re-evaluated depending on the 
current context, but yet avoiding re-typing the expression over and over.  
The first and easiest is to store the expression as a string and use your 
processors "evaluate" extension function to re-evaluate the string over and 
over.

<!-- Store as a string instead of as the select="" attribute -->
<xsl:variable name="condition">*[//author='C. J. Date']</xsl:variable>
<xsl:template ...>
  <!-- This is for Saxon, other processors have other functions -->
  <xsl:if test="saxan:evaluate($condition)">...</xsl:if>
</xsl:template>

But that method is not portable.  If your condition does not change at 
runtime, then you can write the condition as an entity in a DTD.  This 
requires that the condition is totally hard-coded though, but if, for 
example, you wanted to let the user specify the author to test for as a 
param, then you could do it like this:

<!DOCTYPE xsl:stylesheet [
  <!ENTITY condition "*[//author=$author]">
]>
<xsl:stylesheet ...>
  <xsl:param name="author" select="..."/>
  <xsl:template ...>
    <xsl:if test="&condition;">...</xsl:if>
  </xsl:template>
</xsl:stylesheet>

Hope that helps; sorry there has been so much confusion over your question, 
and I hope I'm not confused as well :)

-- 
Peter Davis
How comes it to pass, then, that we appear such cowards in reasoning,
and are so afraid to stand the test of ridicule?
		-- A. Cooper

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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]