使用xsl根据xml输出显示不同的图像

时间:2013-03-26 20:14:20

标签: xml xslt

我有一个xml(我从外部获得)输出:

...<prop name="day">monday</prop>
<prop name="week">2</prop>...

我想知道是否可以使用xsl来显示图像而不是当天的名字?当天的名字将随着7个可能的变量而变化,我需要为一周中的每一天显示不同的图像。

所以我希望的结果是这样的:

 <img src="mondayimage.jpg">
 <p>Week number 2</p>

3 个答案:

答案 0 :(得分:0)

你可以使用xsl:选择处理你的场景。

下面我要包含您可以使用的代码段

<xsl:template match="prop">
    <xsl:variable name="day" select="."/>
    <xsl:choose>
        <xsl:when test="$day='monday'">
            <img src="mondayimage.jpg"/>
        </xsl:when>
       <!-- repeat condition for all the days -->
        <xsl:otherwise>
            <p><xsl:value-of select="@name"/> number <xsl:value-of select="."/> </p>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

答案 1 :(得分:0)

我建议为每种类型的道具使用不同的模板,以便以后更容易更改。您还可以在字符串中的“{}”内使用XSL代码,以获得如下所示的模板:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="root/prop[@name='day']">
        <img src="{.}image.jpg"/>
    </xsl:template>
    <xsl:template match="root/prop[@name='week']">
        <p><xsl:value-of select="concat('Week number ',.)"/></p>
    </xsl:template>
</xsl:stylesheet>

答案 2 :(得分:0)

在xslt 2.0中,你使用索引的xpath函数来生成有效的查找:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>

    <xsl:param name="days" select="('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday')"/>
    <xsl:param name="day-image" select="('image1.png','image2.png','image3.png','image4.png','image5.png','image6.png','image7.png')"/>

    <xsl:template match="/root">
        <root>
            <xsl:apply-templates/>
        </root>
    </xsl:template>

    <xsl:template match="prop[@name='day']">
        <img src="{$day-image[index-of($days, current())]}"/>
    </xsl:template>

    <xsl:template match="prop[@name='week']">
        <p>Week number <xsl:value-of select="."/></p>
    </xsl:template>
</xsl:transform>

Working example

相关问题