スタックオーバーフローに関する私の最初の質問にこんにちは:-)
XSLT の xsl:key 関数で奇妙な動作を経験しました。説明するのは少し難しいですが、実証するのは簡単です。
xsl:key 要素を使用して、2 つの異なるがまったく同一のノードセットにインデックスを付けると、適切にインデックスを作成できません。
このテスト例では、テーブルごとにインデックスが作成されたセルの数を知りたいと考えています。これは、2 つのまったく同じテーブル (@id を除く) を使用した最初の入力です。
<?xml version="1.0" encoding="UTF-8"?>
<test>
<table id="table1">
<cell>Cell 1</cell>
<cell>Cell 2</cell>
<cell>Cell 3</cell>
</table>
<table id="table2">
<cell>Cell 1</cell>
<cell>Cell 2</cell>
<cell>Cell 3</cell>
</table>
</test>
次に、2 番目のテーブルの内容がわずかに異なる 2 番目の入力 (最初のセルには、アンダースコア付きの「cell_1」が含まれています)。
<?xml version="1.0" encoding="UTF-8"?>
<test>
<table id="table1">
<cell>Cell 1</cell>
<cell>Cell 2</cell>
<cell>Cell 3</cell>
</table>
<table id="table2">
<cell>Cell_1</cell>
<cell>Cell 2</cell>
<cell>Cell 3</cell>
</table>
</test>
これが私のXSLTです。同じ現在のparent::tableを共有するセルの数である、各テーブル要素をカウントしています。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:key name="cell" match="//cell" use="parent::table"/>
<xsl:template match="//test">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="table">
<numcells id_table="{@id}">
<xsl:value-of select="count(key('cell', .))"/>
</numcells>
</xsl:template>
</xsl:stylesheet>
そして、これは2つの同一のテーブルを持つ最初の出力です。各テーブルに 3 つではなく 6 つのセルが表示されます。
<?xml version="1.0" encoding="utf-8"?>
<test>
<numcells id_table="table1">6</numcells>
<numcells id_table="table2">6</numcells>
</test>
そして今、2 つの異なるテーブルを持つ 2 番目の出力。各テーブルの 3 つのセルの正しい数が表示されます。
<?xml version="1.0" encoding="utf-8"?>
<test>
<numcells id_table="table1">3</numcells>
<numcells id_table="table2">3</numcells>
</test>
XSLT プロセッサに関連している可能性がありますが、Saxon、Xalan、および XSLTProc でテストしたところ、同じ結果が得られました。
@id を使用して問題を回避できることがわかりました。
<xsl:key name="cell" match="//cell" use="parent::table/@id"/>
その後:
<xsl:value-of select="count(key('cell', @id))"/>
しかし、私はまだこの動作を引き起こしているのだろうかと思っています。説明ありがとうございます!