开发者

XSLT how to choose a template based on an attribute

In a stylesheet I would like to choose a template based on an attribute in the source xml. Unfortunately it looks as if one ca开发者_如何学Cnnot use the mode attribute of apply-templates as this must be a qname literal. Is there any other similar way to do this?

Example:

source xml:

...
<document type="1">
    <item>...</item>
</document>
...

stylesheet:

...
<xsl:template match="document">
    <xsl:apply-templates select="item" mode="{@type}" />
</xsl:template>

<xsl:template match="item" mode="1">
    ...
</xsl:template>

<xsl:template match="item" mode="2">
    ...
</xsl:template>


Easy answer: pattern matching.

<xsl:template match="item[../@type = 'whatever']"/>

Second easy answer: when you need variable or param references (You can't use them in patterns), use xsl:choose instruction.

<xsl:template match="item">
   <xsl:param name="pType"/>
   <xsl:choose>
      <xsl:when test="$pType = 'whatever'">
      </xsl:when>
      <xsl:when test="$pType = 'otherthing'">
      </xsl:when>
   </xsl:choose>
</xsl:template>

Complex answer: use named template reference.

<xsl:variavle name="vTemplate" select="document('')/xsl:template/@name"/>

<xsl:template match="xsl:template/@name[.='typeA']" name="typeA">
   <xsl:param name="pContext"/>
</xsl:template>

<xsl:template match="xsl:template/@name[.='typeB']" name="typeB">
   <xsl:param name="pContext"/>
</xsl:template>

<xsl:template match="document">
   <xsl:apply-templates select="$vTemplate[.='typeA']">
      <xsl:with-param name="pContext" select="item"/>
   </xsl:apply-templates>
</xsl:template>

Or look at Dimitre's FXSL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜