声明一个命名的参数,在 <xsl:stylesheet>
元素或 <xsl:template>
元素中使用。 允许指定默认值。
<xsl:param
name = QName
select = Expression
</xsl:param>
特性
- name
必选。 指定参数的限定名。
- select
属性值为表达式,变量值为计算该表达式得出的对象。 指定此属性后,<xsl:param>
元素必须是空的。
元素信息
备注
<xsl:param>
元素上指定的值是绑定的默认值。 如果调用的模板或样式表包含 <xsl:param>
,传递的参数将替代默认值。
<xsl:param>
元素必须声明为 <xsl:template>
元素的直接子级。 如果未声明为直接子级,<xsl:param>
元素的值将无法访问,并将出错。 例如:
在前一个示例中,<xsl:template>
元素的唯一直接子级是 <strong>
元素。 因此,分析器无法正确计算 <xsl:param>
元素的值,并产生以下错误:
![]() |
---|
此处不能使用关键字 xsl:param。 |
放置此元素以便能在 <xsl:template>
元素的上下文之内对它计算的正确方法如下:
<xsl:template name="getcount">
<xsl:param name="counted">
<xsl:value-of select="count(//book)"/>
</xsl:param>
<xsl:element name="strong">
Total Book Count: <xsl:value-of select="$counted"/>
</xsl:element>
参数值可以是任何表达式可以返回的类型的对象。 <xsl:param>
元素可以通过下列三种备选方法指定变量值:
如果元素具有
select
属性,属性值必须是表达式,参数值是计算该表达式得出的对象。 在这种情况下,元素的内容必须是空的。如果元素没有
select
属性,并且包含非空的内容,例如一个或多个子节点,内容将指定该值。 内容是通过实例化为参数指定值的模板。 值是结果树的一个片断,等效于只包含一个根节点、将通过实例化该模板生成的节点序列作为子节点的节点集。 该结果树片断中的节点的基 URI 是元素的基 URI。如果通过实例化该模板创建的节点序列中的某个成员是属性节点或命名空间节点,将出错,因为根节点不能将属性节点或命名空间节点作为子节点。
如果内容是空的并且没有
select
属性,参数值将为空字符串。 因此<xsl:param name="x"/>
等效于
<xsl:param name="x" select="''"/>
如果使用某个参数按位置选择节点,一定不要执行以下指令:
<xsl:param name="n">2</xsl:param> ... <xsl:value-of select="item[$n]"/>
这将输出第一项元素的值,因为变量“n”将被绑定到结果树的片段上,而不是数字上。 而应执行以下指令:
<xsl:param name="n" select="2"/> ... <xsl:value-of select="item[$n]"/>
或
<xsl:param name="n">2</xsl:param> ... <xsl:value-of select="item[number($n)]"/>
通过以下方式可以方便地将空节点集指定为参数的默认值。
<xsl:param name="x" select="/.."/>
示例
该示例使用参数定义“编号块”的命名模板来控制编号的格式。
XML 文件 (catmat.xml)
XSLT 文件 (paramelem.xsl)
输出
以下是格式化输出:
1. the 2. cat a. sat b. on c. the 3. mat
以下是处理器输出,为了清楚起见,增加了空白。
<?xml version="1.0" encoding="UTF-16"?>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">1. the</fo:block>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">2. cat</fo:block>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">a. sat</fo:block>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">b. on</fo:block>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">c. the</fo:block>
<br xmlns:fo="http://www.w3.org/1999/XSL/Format" />
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format">3. mat</fo:block>
另请参见
参考
<xsl:with-param> 元素
<xsl:variable> 元素
<xsl:call-template> 元素