0

すべての索引用語をセクションごとに検索したいのですが、セクションがネストされています。簡単な例を次に示します。

<chapter>
  <section><title>First Top Section</title>
    <indexterm text="dog"/>
    <para>
      <indexterm text="tree"/>
    </para>
    <section><title>SubSection</title>
      <indexterm text="cat"/>
    </section>
  </section>
  <section><title>Second Top Section</title>
    <indexterm text="elephant" />
  </section>
</chapter>

次のような結果を得る xpath 式はありますか?

First Top Section = ["dog", "tree"]
Subsection = ["cat"]
Second Top Section = ["elephant"]

もちろん、次のような式を使用して、セクションの下にあるすべての子孫索引用語を取得します。

/chapter/section//indexterm

しかし、indexterm は、セクション内の他の要素内にある場合があります。それらは必ずしも子要素ではありません。

xpath を使用して、親セクションに固有の索引用語を取得することは可能ですか?

4

2 に答える 2

1

XPath 2.0 を使用できる場合は、次のことができます。

XML 入力

<chapter>
    <section><title>First Top Section</title>
        <indexterm text="dog"/>
        <para>
            <indexterm text="tree"/>
        </para>
        <section><title>SubSection</title>
            <indexterm text="cat"/>
        </section>
    </section>
    <section><title>Second Top Section</title>
        <indexterm text="elephant" />
    </section>
</chapter>

XPath 2.0

for $section in //section 
return concat($section/title,' - ["',
       string-join($section//indexterm[ancestor::section[1] is $section]/@text,
       '", "'),'"]&#xA;')

出力

First Top Section - ["dog", "tree"]
SubSection - ["cat"]
Second Top Section - ["elephant"]
于 2013-10-10T15:58:49.330 に答える
1

section次のレベルに述語を置くことができます。

/chapter/section[title = 'First Top Section']//indexterm

ただし、これには、サブセクションの要素を含む、指定されたセクションの下のすべての indexterm 要素が含まれます。それらを除外するには、次のようなことができます

/chapter/section[title = 'First Top Section']//indexterm[count(ancestor::section) = 1]

section正確に 1 つの祖先 (つまり、開始した「最初のトップ セクション」)を持つ indexterm 要素を選択します。

より一般的には、特定のsection要素への参照がある場合、最初に評価することにより、サブセクション内ではなく、その内部のすべての indexterm 要素を取得できます

count(ancestor-or-self::section)

数値として、現在のsection要素をコンテキスト ノードとして使用し、別の式を作成します。

.//indexterm[count(ancestor::section) = thenumberyoujustcounted]

section元の要素をコンテキスト ノードとして再度ノード セットとして評価します。

于 2013-10-10T15:42:14.037 に答える