我想创建一个类似的变量:
<xsl:variable name="mytree" >
<foos>
<foo>bar</foo>
<foo>bar</foo>
<foo>bar</foo>
<foo>bar</foo>
<foos>
</xsl:variable>
使用它,如:
<xsl:call-template name="myTemplate">
<xsl:with-param name='aTree' select='$mytree' />
</xsl:call-template>
<xsltemplate name="myTemplate">
<xsl:param name="aTree" />
[My code that treat $aTree like a Tree]
</xsl:template>
我的问题是:是否可以创建一个Tree变量和How?
答案 0 :(得分:3)
要实现这一点,您可能需要使用扩展函数,即 node-set 函数,该函数从结果树片段返回一组节点。
首先,您需要为扩展函数定义名称空间,如此
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
在这种情况下,我使用的是Microsoft扩展功能,但根据您使用的平台,其他功能可用。 (http://exslt.org/common是非Microsoft平台的另一种常见方法)。
然后,您可以像这样访问变量中的元素(作为示例)
<xsl:apply-templates select="msxsl:node-set($aTree)/foos/foo"/>
将这个完全放在一个简单的例子中就可以了解这个
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:variable name="mytree">
<foos>
<foo>bar1</foo>
<foo>bar2</foo>
<foo>bar3</foo>
<foo>bar4</foo>
</foos>
</xsl:variable>
<xsl:template match="/">
<xsl:call-template name="myTemplate">
<xsl:with-param name="aTree" select="$mytree"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="myTemplate">
<xsl:param name="aTree"/>
<newfoos>
<xsl:apply-templates select="msxsl:node-set($aTree)/foos/foo"/>
</newfoos>
</xsl:template>
<xsl:template match="foo">
<newfoo>
<xsl:value-of select="text()"/>
</newfoo>
</xsl:template>
</xsl:stylesheet>
运行时,只会输出以下结果:
<newfoos>
<newfoo>bar1</newfoo>
<newfoo>bar2</newfoo>
<newfoo>bar3</newfoo>
<newfoo>bar4</newfoo>
</newfoos>
鉴于此示例,您没有理由不能首先动态创建 myTree 变量。