XSLT getting last element

XsltXpathMenu

Xslt Problem Overview


I am trying to find the last element in my xml, which looks like:

    <list>
        <element name="A" />
        <element name="B" >
            <element name="C" />
            <element name="D" >
                <element name="D" />
                <element name="E" />
                <element name="F" />
                <element name="G" />
            </element>
        <element name="H" />
        <element name="I" />
    </list>

I need to get some kind of reverse menu, where current element and parents are highlighted as "active" and sibling as "inactive". Instead in result I have a messy tree only when I suppose "D" element clicked.

Double D elements are my problem. When I use select="//element[@name='D'][last()]" or select="//element[@name='D' and last()]" (btw which one is correct?) first time first occurrence of D element is selected (debugger shows that). Here is xsl

<xsl:template match="list">
    <xsl:apply-templates select="//navelement[@name = 'D'][last()]" mode="active"/>
</xsl:template>

<xsl:template match="element">
    <ul class="menu">
	<xsl:apply-templates select="preceding-sibling::node()" mode="inactive"/>
	    <li><a>....</a></li>
	<xsl:apply-templates select="following-sibling::node()" mode="inactive"/>
    </ul>	
    <xsl:apply-templates select="parent::element" mode="active"/>
</xsl:template>

<xsl:template match="element" mode="inactive">
	    <li><a>....</a></li>
</xsl:template>

Xslt Solutions


Solution 1 - Xslt

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNikView Question on Stackoverflow
Solution 1 - XsltRobert ChristieView Answer on Stackoverflow