1

xslt エンジンにいくつかの設計上の問題があります。早速、XML 文書を他の XML 文書に変換しています (最初はメタモデル、2 番目は OpenDocument XML です)。

ある時点で、いくつかの条件に基づいて要素のコンテンツ テキスト ノードを出力したいと考えています。ダミーの例を使用しましょう:

<father haircolor='blond'>
    <son>
        some text
    </son>
    <sister>
        some stupid text
    </sister>
</father>

<son>そして、その親が「金髪の父親」であり、姉妹がフォローしている場合、要素のテキストノードを出力したい

これにはさまざまな解決策があります:

最初は正確なパターンを使用しています:

<xsl:template match="father[haircolor='blond']>...</xsl:template>

<xsl:template match="son[following-sibling::sister]>...</xsl:template>

2 つ目は、テンプレートでモード属性を使用することです。

<xsl:template match="father[haircolor='blond' and son and sister]">
    <xsl:apply-template select='*' mode='ConditionsAreOk'/>
</xsl:template>

3 つ目は、リーフ テンプレートで xsl:if を使用することです。

<xsl:template match="son">
    <xsl:if test="parent::father/@haircolor = 'blond' and following-sibling::sister>
         {.}
    </xsl:if>
</xsl:template>

xslt コードの可読性と保守性に関心があるため、最良の方法を選択したいと考えています。明確にするために、私は「方法」について助けを求めるのではなく、「どの方法が最善か」について尋ねます。

私の実際の考え : 最初の方法が最も純粋な XSLT だと思いますが、条件が複雑で複数の要素がある場合は非常にハードコアになる可能性があります。いくつかの特定のテンプレートを作成する必要があります。特定の一致を持つ複数のテンプレートの代わりに、xsl:if テスト条件にハードコア XPath を持つテンプレートが 1 つだけあるため、最後のテンプレートを優先します。コードもドキュメントも少なくなります (ただし、XPath をドキュメント化する必要があります。そうしないと、5 分で忘れてしまいます...)。

ご意見はありますか?

4

1 に答える 1

1

I strongly recommend to avoid as much as possible explicit conditional instructions and to use template match patterns instead.

In this particular case I'd use:

<xsl:template match="father[haircolor='blond']/son[following-sibling::sister]>
  <!-- your code here -->
</xsl:template>

So, it is just one single template -- not two -- and the code inside the template body has got rid of difficult to read, understand and maintain conditional instructions.

My own principle is:

If the code contains explicit conditional instructions, then it definitely needs improvement.

于 2012-09-30T13:21:20.160 に答える