【问题标题】:Display different image depending on xml output using xsl根据使用 xsl 的 xml 输出显示不同的图像
【发布时间】:2013-03-26 20:14:20
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    在 xslt 2.0 中,您可以使用 index-of 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

    【讨论】:

      【解决方案2】:

      您可以使用 xsl:choose 来处理您的场景。

      下面我包含了你可以使用的代码sn-p

      <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>
      

      【讨论】:

        【解决方案3】:

        我建议为每种类型的道具使用不同的模板,以便以后更轻松地进行更改。您还可以在字符串中的“{}”中使用 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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-06-13
          • 1970-01-01
          • 1970-01-01
          • 2017-03-28
          • 1970-01-01
          • 2012-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多