2012-05-02 59 views
7

我有chapters和嵌套sections一個XML文檔。 我想找到任何部分的第一個二級部分祖先。 這是ancestor-or-self軸中的倒數第二部分。 僞代碼:找到下一個到最後一個節點使用XPath

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

我的選擇:

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

當然,這一直工作到最後一個() - 1未定義(當前節點是first部分)。

如果當前節點低於second部分,我想要的標題second。 否則我想要標題first

+0

給予好評使用DocBook的。 –

回答

4

這個替換您的XPath:

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

既然你已經可以找到在所有情況下正確的節點,除了一個,我更新了您的XPath來找到first部分(or count(ancestor::section)=0),然後選擇([1])的第一個匹配(在相反的文檔順序,因爲我們正在使用的ancestor-or-self軸)。

+0

工作 - 謝謝。試過你的解決方案之後,我想我可以用它來簡化它,但是它似乎總是選擇當前部分。 '祖先或自身:: d:部分[最後() - 1或最後()] [1]' – Tim

+0

@Tim'祖先或自::部[最後() - 布爾型(祖先::部) ] [1]' –

+0

@Aleh,優雅的解決方案! – Tim

2

下面是一個更短和更有效的解決方案

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

這將選擇最後命名的section的可能前兩個最上面的祖先。如果只有一個這樣的祖先,那麼它本身就是最後一個。

下面是一個完整變換

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

當在以下文獻施加該轉化(基於所提供的,但增加了更多的嵌套section元素):

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

正確的結果產生

first --> first 
second --> second 
third --> second 
相關問題