XSLT <xsl:variable> 元素

定義和用法
<xsl:variable> 元素用於聲明局部或全局的變數。
注意:如果作為頂層元素(top-level element)來聲明,就是全局變數。如果在範本內聲明變數,就是局部變數。
注意:一旦您設置了變數的值,就無法改變或修改該值!
提示:您可以通過 <xsl:variable> 元素的內容或通過 select 屬性,向變數添加值!
語法
<xsl:variable
name="name"
select="expression">
<!-- Content:template -->
</xsl:variable>
name="name"
select="expression">
<!-- Content:template -->
</xsl:variable>
屬性
屬性 | 值 | 描述 |
---|---|---|
name | name | 必需。規定變數的名稱。 |
select | expression | 可選。定義變數的值。 |
實例 1
如果設置了 select 屬性,<xsl:variable> 元素就不能包含任何內容。如果 select 屬性含有文字字串,則必須給字串加引號。下麵的兩個例子為變數 "color" 賦值 "red":
<xsl:variable name="color" select="'red'" />
<xsl:variable name="color" select='"red"' />
實例 2
如果 <xsl:variable> 元素只包含 name 屬性,且沒有內容,則變數的值是空字元串:
<xsl:variable name="j" />
實例 3
下麵的實例通過 <xsl:variable> 元素的內容為變數 "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>
<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>
