如何定义XSL变量并在xsl:choose中分配值

时间:2011-09-28 21:22:14

标签: xml xslt

我想在XSL中定义一个名为'category'的变量,为其赋值,并在我的代码中重新使用该变量。 如果objecttype = 1,变量值应为'car' 如果objecttype = 2,则变量值应为'bus'

我怎样才能做到这一点?

<xsl:template match="/">
<html>
<head><style type="text/css">body{font-size:11px;font-family:Verdana;}</style></head>
<body>
Dear
<xsl:for-each select="user">
<xsl:value-of select="firstname"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:if test="middlename != ''"> 
<xsl:value-of select="middlename"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:value-of select="user/lastname"/>,<br/>
<br/>
You have created a company listing for "<xsl:value-of select="user/objecttitle"/>".<br/>
<br/>
Did you know Google uses the number of Facebook 'likes' for webpages in its rankings?<br/>
You can like you page here: 
<xsl:for-each select="user"> 
<xsl:variable name="category"> 
    <xsl:choose> 
        <xsl:when test="objecttype='1'">car</xsl:when> 
        <xsl:when test="objecttype='2'">bus</xsl:when> 
    </xsl:choose> 
</xsl:variable> 
</xsl:for-each> 
<a href="http://www.mydomain.com/{$category}/{user/objectid}/{user/objecturl}">Click here to go to your company listing now.</a><br/>
Kind regards,<br/>
<br/>
<br/>
</body>
</html>
</xsl:template>

1 个答案:

答案 0 :(得分:5)

这是XSL新手的常见错误。正确的方法是:

<xsl:variable name="category">
  <xsl:choose>
    <xsl:when test="objecttype='1'">car</xsl:when>
    <xsl:when test="objecttype='2'">bus</xsl:when>
    ... etc
  </xsl:choose>
</xsl:variable>

在您的示例中,变量是<xsl:when...>标记的本地变量。