proximityFlying
proximityFlying

Reputation: 183

Get the last last value of a node

I am trying to get the last value of a node that belongs to a group.

Given the following XML -

 <books>
 <author>
    <name>R.R.</name>
    <titles>
          <titlename>North</titlename>
          <titlename>King</titilename>
    </titles>
 </author>
 <author>
    <name>R.L.</name>
    <titles>
          <titlename>Dragon</titlename>
          <titlename>Wild</titilename>
    </titles>
</author>
</books>

I assume it would be something like -

 <template match="/">
      <for-each-group select="books/author" group-by="name">
      <lastTitle>
           <name><xsl:value-of select="name"/></name>
           <title><xsl:value-of select="last()/name"/></title>
      </lastTitle
      </for-each-group>
  <template>

Thus the result would be -

 <lastTitle>
      <name>R.R</name>
      <title>King</title> 
 </lastTitle>
 <lastTitle>
      <name>R.L.</name>
      <title>Wild</title> 
 </lastTitle>

How can I produce this result?

Upvotes: 1

Views: 117

Answers (1)

Tim C
Tim C

Reputation: 70618

Instead of doing this

<xsl:value-of select="last()/name"/>

The expression you are looking for is this:

<xsl:value-of select="titles/titlename[last()]"/>

However, it might be worth pointing out, this isn't really a 'grouping' problem. (It would only be a grouping problems if you have two different author elements with the same name). You can actually just use a simple xsl:for-each here

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="/">
      <xsl:for-each select="books/author">
         <lastTitle>
            <name>
               <xsl:value-of select="name"/>
            </name>
            <title>
               <xsl:value-of select="titles/titlename[last()]"/>
            </title>
         </lastTitle>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

Upvotes: 2

Related Questions