我有以下xsl样式表:
<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8"/>
<xsl:template match="/">
<xsl:variable name="elements">
<xsl:call-template name="get-some-nodes"/>
</xsl:variable>
<root>
<values>
<xsl:copy-of select="$elements"/>
</values>
<count>
<xsl:value-of select="count($elements)"/>
</count>
</root>
</xsl:template>
<xsl:template name="get-some-nodes">
<node>1</node>
<node>2</node>
<node>3</node>
</xsl:template>
</xsl:stylesheet>
(应用它的xml无关紧要,它会生成自己的数据)。
此结果(使用xsltproc)是:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.w3.org/1999/xhtml" xmlns:set="http://exslt.org/sets">
<values>
<node>1</node>
<node>2</node>
<node>3</node>
</values>
<count>1</count>
</root>
鉴于被调用模板返回三个节点,我希望“count($ elements)”为3,但它是1。我怀疑可能结果被包含在某种根节点中,但是任何尝试计数($ elements / *)或类似的都失败了,我相信因为$ elements是结果树片段,而不是节点集。
我无法访问任何exslt或xslt2.0的好东西,当然有办法获取存储在变量中的节点数吗?
我也很乐意在不使用中间变量的情况下计算调用模板返回的节点,但我看不出这是怎么回事。
答案 0 :(得分:3)
<xsl:variable name="elements"> <xsl:call-template name="get-some-nodes"/> </xsl:variable> <root> <values> <xsl:copy-of select="$elements"/> </values> <count> <xsl:value-of select="count($elements)"/> </count> </root>
在XSLT 1.0中,每当节点被复制到<xsl:variable>
的主体中时,此变量的内容就是RTF(Result-Tree_fragment),需要转换为常规在使用XPath进一步处理之前的树。
RTF只能使用扩展函数转换为常规树,扩展函数通常命名为xxx:node-set()
,其中xxx
前缀绑定到特定于供应商的命名空间。
要获取此树顶层元素的数量,您需要:
count(xxx:node-set($elements)/*)
以下是一些名称空间,xxx:
经常绑定:
"http://exslt.org/common/"
"urn:schemas-microsoft-com:xslt"
在XSLT 2.0中,RTF“类型”不再存在,您可以:
count($elements/*)
如果未指定$elements
的类型(默认值为document-node()
)
或
count($elements)
如果$elements
的类型指定为element()*