Count the number of elements returned by <call-template>
I have the following xsl stylesheet:
<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> (It doesn't matter which xml you apply it to, it generates its own data).
The result of this (using xsltproc) is:
<?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> Given that the called template returns three nodes, I expected "count ($ elements)" to be 3, but it is one. I suspected that the results might have been wrapped in some kind of root node, but any attempt to make count ($ elements / *) or similar failed, I suppose, because $ elements is a fragment of the result tree, not node-set .
I do not have access to any exslt or xslt2.0 positions, of course, is there a way to get the number of nodes stored in a variable?
I will also be happy to count the nodes returned by the call pattern without using an intermediate variable, but I do not see how this will be possible.
<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> In XSLT 1.0, whenever nodes are copied to the body <xsl:variable> , the contents of this variable are RTF (Result-Tree_fragment) and must be converted to a regular tree before further processing using XPath.
RTF can be converted to a regular tree only by using an extension function, commonly called xxx:node-set() , where the xxx prefix is ββbound to a provider-specific namespace.
To get the number of elements at the top level of this tree, you need:
count(xxx:node-set($elements)/*) Here are a few namespaces to which xxx: often bound :
"http://exslt.org/common/" "urn:schemas-microsoft-com:xslt" In XSLT 2.0 RTF, "type" no longer exists, and you can simply :
count($elements/*) if type $elements not specified (by default document-node() )
or
count($elements) if type $elements is specified as element()*