dwmicksch
asked on
XSLT - How to check for last element
I need a method of checking for the last element in an xml document. For example, here you can see I have three elements of type "PersonConsentGiver." I need an XSL method to check to see if it is the last PersonConsentGiver in the list to make sure that I don't put a comma at the end of the last persons name. My XSLT that I am using is written below the XML :
<PersonConsentGiver>
<FirstName>First</FirstNam e>
<LastName>Last</LastName>
</PersonConsentGiver>
<PersonConsentGiver>
<FirstName>First</FirstNam e>
<LastName>Last</LastName>
</PersonConsentGiver>
<PersonConsentGiver>
<FirstName>First</FirstNam e>
<LastName>Last</LastName>
</PersonConsentGiver>
<xsl:template match="Document/PersonCons entGiver" mode="ConsentGivers">
<xsl:value-of select="FirstName"/> <xsl:text> (</xsl:text><xsl:value-of select="LastName"/> <xsl:text>), </xsl:text>
</xsl:template>
<PersonConsentGiver>
<FirstName>First</FirstNam
<LastName>Last</LastName>
</PersonConsentGiver>
<PersonConsentGiver>
<FirstName>First</FirstNam
<LastName>Last</LastName>
</PersonConsentGiver>
<PersonConsentGiver>
<FirstName>First</FirstNam
<LastName>Last</LastName>
</PersonConsentGiver>
<xsl:template match="Document/PersonCons
<xsl:value-of select="FirstName"/> <xsl:text> (</xsl:text><xsl:value-of select="LastName"/> <xsl:text>), </xsl:text>
</xsl:template>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
you could use functions like position() and last()
but the way your template is currently set up, those functions would count the whitespace text nodes as well
if you just pass the used nodeset to the PersonConsentGiver template
it would not count the white-space nodes, and you would have correct counts
you can do that with a selective apply-templates
here is an example
(I add newlines because you loose them in the selective apply-templates)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:param name="newline"><xsl:text>
</xsl:text></xsl:param>
<xsl:template match="Document">
<xsl:apply-templates select="PersonConsentGiver
</xsl:template>
<xsl:template match="PersonConsentGiver"
<xsl:value-of select="FirstName"/> <xsl:text> (</xsl:text><xsl:value-of select="LastName"/> <xsl:text>)</xsl:text>
<xsl:if test="not(position() = last())"><xsl:text>,</xsl:
<xsl:value-of select="$newline"/>
</xsl:template>
</xsl:stylesheet>
you see, if you pass the correct nodeset, it is just a simple test to add the comma
Cheers!
Gertone