1

ID属性を介した多対多の関係を持つxmlスニペットがあります。例は次のようになります。

<root>
  <foolist name="firstlist">
    <foo barid="1" someval="some"/>
    <foo barid="1" someval="other"/>
    <foo barid="2" someval="third"/>
  </foolist>
  <foolist name="secondlist">
  <!-- there might be more foo's here that reference the same
       bars, so foo can't be a child of bar -->
  </foolist>
  <bar id="1" baz="baz" qux="qux"/>
  <bar id="2" bax="baz2" qux="qux2"/>
</root>

次のものを取り出したいとします。

baz-some-qux
baz-other-qux
baz2-third-qux2

(つまり、参照された項目から baz と qux の値の間に someval の値を挿入します)、どうすればよいですか? バーのテンプレートを使用する場合は、2 つの異なるテンプレートが必要になります。ここではおそらく本当に基本的なことが欠けているので、事前にお詫び申し上げます。

(編集: 拡張例)

4

2 に答える 2

2

キーを使用した効率的なソリューション

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kFooById" match="foo" use="@barid"/>

 <xsl:template match="bar">
  <xsl:apply-templates select="key('kFooById', @id)" mode="refer">
    <xsl:with-param name="pReferent" select="."/>
  </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="foo" mode="refer">
  <xsl:param name="pReferent" select="/.."/>

  <xsl:value-of select=
   "concat($pReferent/@baz,'-',@someval,'-',$pReferent/@qux,'&#xA;')"/>
 </xsl:template>
</xsl:stylesheet>

この変換が提供されたXMLドキュメントに適用される場合(整形式に修正):

<root>
  <foolist name="firstlist">
    <foo barid="1" someval="some"/>
    <foo barid="1" someval="other"/>
    <foo barid="2" someval="third"/>
  </foolist>
  <foolist name="secondlist">
  <!-- there might be more foo's here that reference the same
       bars, so foo can't be a child of bar -->
  </foolist>
  <bar id="1" baz="baz" qux="qux"/>
  <bar id="2" baz="baz2" qux="qux2"/>
</root>

必要な正しい結果が生成されます。

baz-some-qux
baz-other-qux
baz2-third-qux2
于 2013-01-09T13:39:38.643 に答える
1

これでうまくいくはずです:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="foo">
      <xsl:variable name="matchingBar" select="../../bar[@id = current()/@barid]" />
      <xsl:value-of select="concat($matchingBar/@baz, '-', ./@someval, '-', $matchingBar/@qux, '&#xA0;')" />
    </xsl:template>
</xsl:stylesheet>
于 2013-01-09T10:39:40.727 に答える