首页 > 解决方案 > 如何通过@variable在xsl中添加样式属性

问题描述

我有一个变量@expectedLength。我需要将其分配给样式属性。

            <xsl:if test="@expectedLength">
               <xsl:attribute name="style">
                  <xsl:value-of select="'width:200px'"/>
               </xsl:attribute>
            </xsl:if>

我需要用@expectedLength 的值替换200。如何使用变量?

标签: xslt

解决方案


您可以将您的代码段更改为

<xsl:if test="@expectedLength">
  <xsl:attribute name="style">width: <xsl:value-of select="@expectedLength"/>;</xsl:attribute>
</xsl:if>

这应该适用于任何版本的 XSLT。

在 XSLT 2 及更高版本中,您还可以使用select表达式

<xsl:if test="@expectedLength">
  <xsl:attribute name="style" select="concat('width: ', @expectedLength, ';')"/>
</xsl:if>

我更愿意并建议设置一个模板

<xsl:template match="@expectedLength">
  <xsl:attribute name="style" select="concat('width: ', @expectedLength, ';')"/>
</xsl:template>

然后确保处理任何属性节点。


推荐阅读