find next-to-last node with xpath

我怕爱的太早我们不能终老 提交于 2019-12-22 04:39:17

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/10420638/find-next-to-last-node-with-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!