XSL:Number count not working as expected -- Issue with my XPath?
Here's the XML
<row>
<cell>blah blah</cell>
<check>
<option/>
<optio开发者_Go百科n/>
<option/>
<option/>
<option/>
<option/>
</check>
</row>
Here is the XSL
<xsl:template match="row">
<xsl:variable name="inputLevel">
<xsl:number count="option" level="any" from="."/>
</xsl:variable>
<xsl:value-of select="$inputLevel"/>
</xsl:template>
All I get is "0". http://www.w3schools.com/XPath/xpath_syntax.asp says "." means the current node. Shouldn't it be returning "6"?
Edit1: I wanted to look for option tags at ANY level, not just check. Should have explained but the option tags could exist at any level below
If you want to count descendant option
s you shouldn't use xsl:number
but:
<xsl:variable name="inputLevel" select="count(.//option)">
I think the problem is that the xpath expression option
won't match anything at the row
element - try this instead:
<xsl:number count="check/option" level="any" from="." />
To look for option
elements at any level use the following syntax:
<xsl:number count="//option" level="any" from="." />
I don't think the from
attribute is reqired, and the level
attribute probably isn't doing what you think it is (I'm also not sure what it does...)
From the XSLT 1.0 W3C specification:
"If no
value
attribute is specified, then thexsl:number element
inserts a number based on the position of the current node in the source tree. The following attributes control how the current node is to be numbered:The
level
attribute specifies what levels of the source tree should be considered; it has the valuessingle
,multiple
orany
. The default issingle
.The
count
attribute is a pattern that specifies what nodes should be counted at those levels. If count attribute is not specified, then it defaults to the pattern that matches any node with the same node type as the current node and, if the current node has an expanded-name, with the same expanded-name as the current nodeWhen
level="any"
, it constructs a list of length one containing the number of nodes that match thecount
pattern and belong to the set containing the current node and all nodes at any level of the document that are before the current node in document order, excluding any namespace and attribute nodes (in other words the union of the members of the preceding and ancestor-or-self axes). If thefrom
attribute is specified, then only nodes after the first node before the current node that match the from pattern are considered. ".
From this text it is clear that only nodes that are ancestors or are preceding the current node are counted.
In this question, the current node is the top element node row
and it has 0 ancestor and 0 preceding element nodes.
Therefore, the returned result is correct!
Solution:
Use:
count(descendant::option)
The result of evaluating this expression is the count of all option
elements in the document, that are descendents of the current node (the row
element).
精彩评论