当XML文档中有颜色时,如何向XSL中的Div添加颜色

时间:2018-10-04 20:37:52

标签: xslt

我有一个XSL 1.0文档,其中包含以下内容:

<div class="workgroup_title">
  <xsl:value-of select="./@name"/>
</div>

我需要为此元素设置颜色。颜色在XML文件中

<abc.xyz.color>FF5733</abc.xyz.color>

要得到它,我使用这个:

<xsl:value-of select="./abc.xyz.color"/>

我想做的是

<div class="workgroup_title" style="color:"#<xsl:value-of select="./abc.xyz.color"/>>
  <xsl:value-of select="./@name"/>
</div>

但这是不允许的。

或者:

<xsl:attribute style="color:">#<xsl:value-of select="./abc.xyz.color"/></xsl:attribute>

但是color并不是可以这样设置的属性之一。

2 个答案:

答案 0 :(得分:1)

您可以使用属性值模板来计算文字结果元素的值(部分):<div style="color: #{abc.xyz.color}">...</div>

答案 1 :(得分:1)

以下模板足以满足您的需求:

<xsl:template match="text()" />                      <!-- Removes the text from the <abc.xyz.color>FF5733</abc.xyz.color> element -->

<xsl:template match="/*">                            <!-- Copies the root element and its namespace -->
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
</xsl:template>  

<xsl:template match="div[@class='workgroup_title']"> <!-- Applies the template to the <div> element -->
    <xsl:copy>
        <xsl:attribute name="style"><xsl:value-of select="concat('color: #',../abc.xyz.color,';')"/></xsl:attribute>
        <xsl:copy-of select="node()|@*" />
    </xsl:copy>
</xsl:template>

其输出为:

<root xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <div style="color: #FF5733;" class="workgroup_title">
        <xsl:value-of select="./@name"/>
    </div>
</root>