xsltlife
xsltlife

Reputation: 163

Select various positions of nodes in XSLT

I want to select the first element and use @type='first', Last element @type='last', elements between fist and last @type='middle'

Input:

<disp-quote>
  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>
  <p>Text 4</p>
</disp-quote>

Desired output :

<p type="first">Text 1</p>
<p type="middle">Text 2</p>
<p type="middle">Text 3</p>
<p type="last">Text 4</p>

Tried code :

<xsl:template match="disp-quote/p">
 <p>
   <xsl:attribute name="type">
       <xsl:value-of select="self:p/position()"/>
   </xsl:attribute>
   <xsl:apply-templates/>
 </p>
</xsl:template>

But the output is not working as expected. Please help to solve this. Thank you. I am using XSLT 2.0

Upvotes: 0

Views: 51

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 116992

Why not simply:

        <p>
            <xsl:attribute name="type">
                <xsl:choose>
                    <xsl:when test="position()=1">first</xsl:when>
                    <xsl:when test="position()=last()">last</xsl:when>
                    <xsl:otherwise>middle</xsl:otherwise>
                </xsl:choose>
            </xsl:attribute>
        </p>

Upvotes: 0

Sam
Sam

Reputation: 841

you can try this choose when condition

<xsl:template match="disp-quote/p">
    <xsl:copy>
        <xsl:attribute name="type">
            <xsl:choose>
                <xsl:when test="not(preceding-sibling::p)">
                    <xsl:value-of select="'first'"/>
                </xsl:when>
                <xsl:when test="not(following-sibling::p)">
                    <xsl:value-of select="'last'"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="'middle'"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

Upvotes: 1

Related Questions