【发布时间】:2014-08-26 11:40:01
【问题描述】:
我想应用一个模板,但只适用于第一个匹配项。假设我有一个像这样的 xml:
<cd>
<title>Red</title>
<artist>The Communards</artist>
<country>UK</country>
<company>London</company>
<price>7.80</price>
<year>1987</year>
</cd>
<cd>
<artist>Joe Cocker</artist>
<country>USA</country>
<company>EMI</company>
<price>8.20</price>
<year>1987</year>
</cd>
请注意,第二张 CD 没有标题节点。 和 xsl:
<xsl:template match="title">
Title: <xsl:value-of select="."/><br/>
</xsl:template>
<xsl:template match="artist">
Artist: <xsl:value-of select="."/><br/>
</xsl:template>
如果有节点标题,我想应用该模板,否则我想为艺术家应用模板。我正在尝试类似
<xsl:apply-templates select="title | artist"/>
但是它会同时使用这两个,我只希望应用第一个。因此,如果有标题,请使用该标题,否则使用艺术家。是否可以通过这种方式或仅使用<xsl:choose> 来完成?
【问题讨论】:
-
match="artist[not(preceding-sibling::title or following-sibling::title)]"? -
@biziclop 这意味着 XML 始终处于相同的顺序,(在我的情况下)它不是。或者至少我不能依赖它。
-
不,这意味着艺术家模板只有在没有名为
title的(之前或之后的)兄弟姐妹时才会匹配。它相当于artist[not(../title)],但更好地展示了这个想法。 -
@biziclop 你是对的,对不起。我认为它必须是直接在之前或之后。