In XPath, is there any difference between the count() and last() functions? If you had a nodeset of 3 elements they would both return the value 3, correct? It's just that count() returns the number of nodes and last() returns the position of the last node. But, wouldn't these always be the same, or is there something more subtle that I am missing?
Jeff, Have a look at the xml file and the following stylesheet - =============================================== <!-- XML document --> <source> <AAA> <BBB> <CCC>Carl</CCC> </BBB> <BBB/> <BBB/> </AAA> <AAA> <BBB/> <BBB> <CCC attr="1">John</CCC> <CCC attr="2">Charles</CCC> <CCC>Robert</CCC> <CCC>Anthony</CCC> </BBB> </AAA> </source> ======================================= <!-- XSL stylesheet --> <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="/"> <xsl:call-template name="showDifference"/> </xsl:template> <xsl:template name="showDifference"> <p> <xsl:text> Count of all CCC elements ::</xsl:text> <xsl:value-of select ="count(//CCC)"/> </p> <p> <xsl:text> Count of all CCC elements with attribute "attr" ::</xsl:text> <xsl:value-of select ="count(//CCC[@attr])"/> </p> <xsl:apply-templates select="//AAA[last()]//BBB[last()]//CCC"/> </xsl:template> </xsl:stylesheet> ========EXPLANATION FOLLOWS=============== 1) The first difference is that count( ) requires a nodeset as input. The above xml file has 5 CCC elements in total and you can see the output by running it thru an xslt processor 2) last( ) function returns the size of the current context. If we look at the xpath expression in the above example, select="//AAA[last()]//BBB[last()]//CCC"/> This means that select all the child CCC elements, of the last of the BBB child of the last AAA parent. 3) count ( ) has nothing to do with the context and just returns the no. of nodes that satisfy a given xpath expression; hence the expression - <xsl:value-of select ="count(//CCC[@attr])"/> returns a value of 2 as there are two CCC nodes in the xml document with "attr" as the attribute name. I hope that this answers your question
As the big book says (XML in a nutshell) - The last() function returns the number of nodes in the context node set, which is the same as the position of the last node in the set. The count() function is similar, except that it returns the number of nodes in its node set argument rather than in the context node list. Cheers, Dan
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
For my next trick, I'll need the help of a tiny ad ...