Friday, December 19, 2008

XSLT note 3 - variable

You can basically build a variable just as building any output. The simple way is

<xsl:variable name="v" select="xpath-expression" />

But you don't have to use select. Yiou can construct your variable in the constructor. Following is some sample

<xsl:variable name="Subtotals"> <!-- consturctor: can be any markup --> <xsl:for-each select="Row"> <number> <xsl:value-of select="Quantity * Price"/> </number> </xsl:for-each> </xsl:variable> <xsl:variable name="header"> <h1 style="color:red;">This is demo</h1> </xsl:variable> <xsl:variable name="tmpResult"> <xsl:apply-templates select="$orderRow" /> </xsl:variable>

How to use variable

If a variable contains a set of nodes. you can use the variable in other XPath expressions without any limitations. For example,

<xsl:variable name="books" select="//book"/> <xsl:for-each select="$books/author"> </xsl:for-each> <!-- same as <xsl:for-each select="//book/author"> </xsl:for-each> -->

If you are using constructor to build a constructor, the variable can hold any arbitrary content, this content is called result tree fragment. You can imagine a result tree fragment (RTF) as a fragment or a chunk of XML code. You can assign a result tree fragment to a variable directly, or result tree fragment can arise from applying templates or other XSLT instructions. The following code assigns a simple fragment of XML to the variable $author.

<xsl:variable name="author"> <firstname>Jirka</firstname> <surname>Kosek</surname> <email>jirka@kosek.cz</email> </xsl:variable>

Now let's say we want to extract the e-mail address from the $author variable. The most obvious way is to use an expression such as $author/email. But this will fail, as you can't apply XPath navigation to a variable of the type "result tree fragment."

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" extension-element-prefixes="exsl" version="1.0"> ... <!-- Now we can convert result tree fragment back to node-set --> <xsl:value-of select="msxsl:node-set($author)/email"/> ... </xsl:stylesheet>

If you don't reuse the content of result tree, you can put copy-of statement to where you want your output to be.

<xsl:copy-of select="$header"/>

variable has a scope, like the following example shows, the $castList is referenced outside of the definition scope, so it is illegal.

<xsl:template match="Program" mode="Details"> <p> <xsl:variable name="castList" select="CastList" /> <xsl:apply-templates select="$castList" mode="DisplayToggle" /> </p> <xsl:apply-templates select="$castList" /> </xsl:template>

No comments:

Post a Comment