计算<call-template>返回的元素数

gfx*_*onk 5 xslt count

我有以下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>
Run Code Online (Sandbox Code Playgroud)

(应用它的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>
Run Code Online (Sandbox Code Playgroud)

鉴于被调用的模板返回三个节点,我预计"count($ elements)"为3,但它是1.我怀疑结果可能被包含在某种根节点中,但任何尝试计数($ elements/*)或类似的都失败了,我相信因为$ elements是结果树片段,而不是节点集.

我无法访问任何exslt或xslt2.0的好东西,当然有办法获取存储在变量中的节点的数量吗?

我也很乐意在不使用中间变量的情况下计算调用模板返回的节点,但我看不出这是怎么回事.

Dim*_*hev 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>
Run Code Online (Sandbox Code Playgroud)

在 XSLT 1.0 中,每当将节点复制到 的主体中时<xsl:variable>,该变量的内容都是 RTF (Result-Tree_fragment),并且需要在使用 XPath 进一步处理之前转换为常规树。

仅使用扩展函数(通常名为 )即可将 RTF 转换为常规树xxx:node-set(),其中xxx前缀绑定到特定于供应商的命名空间。

要获取此树顶层的元素数量,您需要:

count(xxx:node-set($elements)/*)
Run Code Online (Sandbox Code Playgroud)

以下是一些xxx:经常绑定的命名空间:

"http://exslt.org/common/"

"urn:schemas-microsoft-com:xslt"
Run Code Online (Sandbox Code Playgroud)

在 XSLT 2.0 中,RTF“类型”不再存在,您可以

count($elements/*)
Run Code Online (Sandbox Code Playgroud)

如果未指定 的类型$elements(默认为document-node()

或者

count($elements)
Run Code Online (Sandbox Code Playgroud)

如果 的类型$elements指定为element()*