我只有基本的XSLT技能,如果这是基本的或不可能的,请原谅。
我有一个paginator模板,它在我正在查看的网站上无处不在。有一个bug,一个特定的搜索需要有一个categoryId参数附加到页面链接的href。我不能改变分页器样式表,否则我就给它添加一个参数。我想做的是应用模板,然后根据它的输出做第二次转换。这可能吗?其他人通常是如何扩展库模板的?
到目前为止,我已经考虑对输出进行递归复制,并在处理href时将模板应用于它们。这个语法让我有点迷惑,特别是我甚至不确定它是否可能。编辑-在Dabbler的回答和Michael Kay的评论之间,我们得到了答案。这是我的完整测试。
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common">
<!-- note we require the extensions for this transform -->
<!--We call the template to be extended here and store the result in a variable-->
<xsl:variable name="output1">
<xsl:call-template name="pass1"/>
</xsl:variable>
<!--The template to be extended-->
<xsl:template name="pass1">
<a href="url?param1=junk">foo</a>
</xsl:template>
<!--the second pass. we lock this down to a mode so we can control when it is applied-->
<xsl:template match="a" mode="pass2">
<xsl:variable name="href" select="concat(@href, '&', 'catid', '=', 'stuff')"/>
<a href="{$href}"><xsl:value-of select="."/></a>
</xsl:template>
<xsl:template match="/">
<html><head></head><body>
<!--the node-set extension function turns the first pass back into a node set-->
<xsl:apply-templates select="ext:node-set($output1)" mode="pass2"/>
</body></html>
</xsl:template>
</xsl:stylesheet>
下面是使用XSLT 1.0如何完成多通道处理的完整示例:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node()|@*" mode="mPass2">
<xsl:copy>
<xsl:apply-templates select="node()|@*" mode="mPass2"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:variable name="vrtfPass1Result">
<xsl:apply-templates/>
</xsl:variable>
<xsl:apply-templates mode="mPass2"
select="ext:node-set($vrtfPass1Result)/*"/>
</xsl:template>
<xsl:template match="num/text()">
<xsl:value-of select="2*."/>
</xsl:template>
<xsl:template match="/*" mode="mPass2">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates mode="mPass2"/>
</xsl:copy>
</xsl:template>
<xsl:template match="num/text()" mode="mPass2">
<xsl:value-of select="3 + ."/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于以下XML文档:
<nums>
<num>01</num>
<num>02</num>
<num>03</num>
<num>04</num>
<num>05</num>
<num>06</num>
<num>07</num>
<num>08</num>
<num>09</num>
<num>10</num>
</nums>
产生所需的结果(每个num
乘以2
,在下一阶段将3
添加到每个num
) :
<nums>
<num>5</num>
<num>7</num>
<num>9</num>
<num>11</num>
<num>13</num>
<num>15</num>
<num>17</num>
<num>19</num>
<num>21</num>
<num>23</num>
</nums>
这在XSLT 2中是可能的;你可以把数据存储在一个变量中,然后在这个变量上调用apply-templates。
基本例子:
<xsl:variable name="MyVar">
<xsl:element name="Elem"/> <!-- Or anything that creates some output -->
</xsl:variable>
<xsl:apply-templates select="$MyVar"/>
在样式表的某个地方有一个与Elem匹配的模板。您还可以使用单独的模式来明确区分两个阶段(构建变量和处理变量),特别是当两个阶段都使用匹配相同节点的模板时。