XSLT <xsl:variable> 元素
定義和用法
<xsl:variable> 元素用于聲明局部或全局的變量。
注釋:如果被聲明為頂層元素,則該變量是全局的,而如果在模板內(nèi)聲明,則變量是本地的。
注釋:一旦您設(shè)置了變量的值,就無法改變或修改該值!
提示:您可以通過 <xsl:variable> 元素的內(nèi)容或通過 select 屬性,向變量添加值!
語法
<xsl:variable name="name" select="expression"> <!-- Content:template --> </xsl:variable>
屬性
屬性 | 值 | 描述 |
---|---|---|
name | name | 必需。規(guī)定變量的名稱。 |
select | expression | 可選。定義變量的值。 |
實例
例子 1
如果設(shè)置了 select 屬性,<xsl:variable> 元素就不能包含任何內(nèi)容。如果 select 屬性含有文字字符串,則必須給字符串加引號。
下面的兩個例子為變量 "color" 賦值 "red":
<xsl:variable name="color" select="'red'"
/>
<xsl:variable name="color" select='"red"'
/>
例子 2
如果 <xsl:variable> 元素只包包含 name 屬性,且沒有內(nèi)容,則變量的值是空字符串:
<xsl:variable name="j" />
例子 3
下面的例子通過 <xsl:variable> 元素的內(nèi)容為變量 "header" 賦值:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:variable name="header">
<tr> <th>Element</th> <th>Description</th> </tr></xsl:variable>
<xsl:template match="/"> <html> <body> <table> <xsl:copy-of select="$header" /> <xsl:for-each select="reference/record"> <tr> <xsl:if category="XML"> <td><xsl:value-of select="element"/></td> <td><xsl:value-of select="description"/></td> </xsl:if> </tr> </xsl:for-each> </table> <br /> <table> <xsl:copy-of select="$header" /> <xsl:for-each select="table/record"> <tr> <xsl:if category="XSL"> <td><xsl:value-of select="element"/></td> <td><xsl:value-of select="description"/></td> </xsl:if> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>