带有for-each语句的xsl条件标记

时间:2014-11-05 02:15:37

标签: xml xslt

这是我的xml文件:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="question.xsl"?>
<root>
        <overall_test>
                <overall_name>
                         Movies

                </overall_name>
                <overall_result>
                         PASSED 

                </overall_result>
        </overall_test>
        <subtest>
                <name>
                         Matrix

                </name>
                <result>
                         PASSED

                </result>
        </subtest>
        <subtest>
                <name>
                         Die Hard

                </name>
                <result>
                         FAILED

                </result>
        </subtest>
        <subtest>
                <name>
                         Terminator

                </name>
                <result>
                         PASSED 

                </result>
        </subtest>
        <subtest>
                <name>
                         Avataar 

                </name>
                <result>
                         FAILED

                </result>
        </subtest>
</root>

xsl文件在这里:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <xsl:for-each select="root/overall_test">
  <h2>Overall test name:<xsl:value-of select="overall_name"/></h2>
  <h2>Overall test result:<xsl:value-of select="overall_result"/></h2>
  </xsl:for-each>
    <table border="1">
      <tr bgcolor="#gray">
        <th>Sub test name</th>
        <th>Sub Test Result</th>

      </tr>
      <xsl:for-each select="root/subtest">
      <tr>
        <td><xsl:value-of select="name"/></td>
        <td><xsl:value-of select="result"/></td>

      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

这是xml在浏览器中查找的方式(这与IE中的表格有关):

Overall test name: Movies 
Overall test result: PASSED 
Sub test name Sub Test Result 
Matrix  PASSED  
Die Hard  FAILED  
Terminator  PASSED  
Avataar  FAILED  

我需要为&#34; PASSED&#34;并且&#34;失败&#34;部分为绿色和红色,具体取决于标签的值。我尝试使用xsl:choose,xsl:when,但最终弄乱了文件。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

尝试更换:

<td><xsl:value-of select="result"/></td>

使用:

<td>
    <xsl:attribute name="bgcolor">
         <xsl:choose>
            <xsl:when test="normalize-space(result)='PASSED'">green</xsl:when>
            <xsl:otherwise>red</xsl:otherwise>
        </xsl:choose>
    </xsl:attribute>
    <xsl:value-of select="result"/>
</td>