Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find next-to-last node with xpath

I have a XML document with chapters and nested sections. I am trying to find, for any section, the first second-level section ancestor. That is the next-to-last section in the ancestor-or-self axis. pseudo-code:

<chapter><title>mychapter</title>
  <section><title>first</title>
     <section><title>second</title>
       <more/><stuff/>
     </section>
  </section>
</chapter>

my selector:

<xsl:apply-templates 
    select="ancestor-or-self::section[last()-1]" mode="title.markup" />

Of course that works until last()-1 isn't defined (the current node is the first section).

If the current node is below the second section, i want the title second. Otherwise I want the title first.

like image 482
Tim Avatar asked May 02 '12 19:05

Tim


2 Answers

Replace your xpath with this:

ancestor-or-self::section[position()=last()-1 or count(ancestor::section)=0][1]

Since you can already find the right node in all cases except one, I updated your xpath to also find the first section (or count(ancestor::section)=0), and then select ([1]) the first match (in reverse document order, since we are using the ancestor-or-self axis).

like image 84
Jason Clark Avatar answered Oct 20 '22 23:10

Jason Clark


Here is a shorter and more efficient solution:

(ancestor-or-self::section[position() > last() -2])[last()]

This selects the last of the possibly first two topmost ancestors named section. If there is only one such ancestor, then it itself is the last.

Here is a complete transformation:

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

 <xsl:template match="section">
  <xsl:value-of select="title"/>
  <xsl:text> --> </xsl:text>

  <xsl:value-of select=
  "(ancestor-or-self::section[position() > last() -2])[last()]/title"/>
  <xsl:text>&#xA;</xsl:text>
  <xsl:apply-templates/>
 </xsl:template>

 <xsl:template match="text()"/>
</xsl:stylesheet>

When this transformation is applied on the following document (based on the provided, but added more nested section elements):

<chapter>
    <title>mychapter</title>
    <section>
        <title>first</title>
        <section>
            <title>second</title>
            <more/>
            <stuff/>
        <section>
            <title>third</title>
        </section>
        </section>
    </section>
</chapter>

the correct results are produced:

first --> first
second --> second
third --> second
like image 35
Dimitre Novatchev Avatar answered Oct 21 '22 00:10

Dimitre Novatchev