在XSLT中选择节点的不同位置

在XSLT中选择节点的不同位置,xslt,Xslt,我想选择第一个元素并使用@type='first',最后一个元素@type='Last',第一个元素和最后一个元素之间的元素@type='middle' 输入: <disp-quote> <p>Text 1</p> <p>Text 2</p> <p>Text 3</p> <p>Text 4</p> </disp-quote> 文本1 文本2 文本3 文本4

我想选择第一个元素并使用
@type='first'
,最后一个元素
@type='Last'
,第一个元素和最后一个元素之间的元素
@type='middle'

输入:

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

文本1

文本2

文本3

文本4

期望输出:

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

文本2

文本3

文本4

试用代码:

<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>



但是输出并没有如预期的那样工作。请帮忙解决这个问题。非常感谢。我使用的是XSLT2.0,您可以在条件满足时尝试此选项

<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>

为什么不简单地:

        <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>

第一
最后的
中间的


我看到Position的拼写错误。应该是position@PraveenHassan对不起,我打错了。但问题仍然存在