7

chaptersがネストされたXMLドキュメントがありますsections。私は、どのセクションでも、最初の第2レベルのセクションの祖先を見つけようとしています。ancestor-or-selfこれは、軸の最後から2番目のセクションです。擬似コード:

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

もちろん、これはlast()-1が定義されていないまで機能します(現在のノードはfirstセクションです)。

現在のノードがsecondセクションの下にある場合は、タイトルが必要ですsecond。それ以外の場合は、タイトルが必要ですfirst

4

2 に答える 2

5

xpathを次のように置き換えます。

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

1つを除くすべてのケースですでに正しいノードを見つけることができるので、xpathを更新してセクション( )見つけ、最初の一致を選択( )します(軸 を使用しているため、ドキュメントの逆順)。firstor count(ancestor::section)=0[1]ancestor-or-self

于 2012-05-02T20:17:04.947 に答える
2

これがより短く、より効率的な解決策です:

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

これにより、。という名前の最初の2つの最上位の祖先の最後が選択されsectionます。そのような祖先が1つしかない場合は、それ自体が最後になります。

これが完全な変換です:

<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
于 2012-05-03T02:56:47.963 に答える