Jump to content

XPATH count()


tommyinnz
 Share

Recommended Posts

Hi everyone.I am trying to use count function to count different names in my xml file.my xml file like this:<p> <name>jack/name> <name>jan</name> <name>jack</name></p>and in my xslt file, i am using <xsl:value-of select="count(/p/name)" />but this gives me 3, what i need is to only count different names, which, in this case it should return 2.Thanks for any help.

Link to comment
Share on other sites

  • 2 weeks later...

@tommyinnz what do you mean you got it? Were you able to run that function? If so- how?

Link to comment
Share on other sites

  • 2 weeks later...

This may not be the best way but it is one method which works with version 1 and the sample XML you gave. This is my first post so i hope it inserts the code neatly.<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.1" xmlns:str="http://exslt.org/strings"><xsl:output method="text" indent="no"/><xsl:variable name="newline" select="' '"/><xsl:key name="names" match="name" use="text()"/> <xsl:template match="/"> <xsl:for-each select="p/name[generate-id() = generate-id(key('names',text())[1])]"> <xsl:variable name="currentName" select="text()"/> <!-- print output --> <xsl:value-of select="text()"/> <xsl:value-of select="': '"/> <xsl:value-of select="count(//name[text() = $currentName])"/> <xsl:value-of select="$newline"/> </xsl:for-each> </xsl:template></xsl:stylesheet>

Link to comment
Share on other sites

This may look a bit better - the code is the same i have just added the code correctly into tags nowThe XML is:

<p>   <name>jack</name>   <name>jack</name>   <name>jan</name>   <name>jack</name>   <name>jack</name></p>

The XSL is:

<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.1"  xmlns:str="http://exslt.org/strings"><xsl:output method="text" indent="no"/><xsl:variable name="newline" select="''"/><xsl:key name="names" match="name" use="text()"/>	<xsl:template match="/">  <xsl:for-each select="p/name[generate-id() = generate-id(key('names',text())[1])]"> 	 <xsl:variable name="currentName" select="text()"/> 	 <!-- print output --> 	 <xsl:value-of select="text()"/> 	 <xsl:value-of select="': '"/> 	 <xsl:value-of select="count(//name[text() = $currentName])"/> 	 <xsl:value-of select="$newline"/>  </xsl:for-each>	</xsl:template></xsl:stylesheet>

The Output is:jack: 4jan: 1

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...