首页 > 解决方案 > XSL:无法根据条件将值填充到 HTML

问题描述

我在准备正确的 XSLT 模板以将值填充到 HTML 时遇到问题。在我的情况下,我想填充列Test2的值,当它是它的验证类型时。

我的 XSL 模板部分是:

<xsl:for-each select="CurrentFile/RejRow[Col/ValidationType='Task: Non-Numeric']">
<tr>
  <td>
     <span>
        <xsl:value-of select="Col/ColVal"/>
     </span>
  </td>
</tr>
</xsl:for-each>

XML 是:

<CurrentFile>
    <RejRow>
        <Col>
            <ColName>Test1</ColName>
            <ColVal>TestVal1</ColVal>
        </Col>
        <Col>
            <ColName>Test2</ColName>
            <ColVal>TestVal2</ColVal>
            <ValidationType>Task: Non-Numeric</ValidationType>
        </Col>
    </RejRow>
</CurrentFile>

更新:当我需要检查具有多个验证的多个列并仅输出未通过它的列时,我当前的答案不适用于这种情况。仍然需要帮助。

这种方法对我不起作用:

<xsl:for-each select="RejRow[count(Col/ValidationType)!=0]">
<tr>
  <xsl:for-each select="Col[ColName='Test2']">
    <xsl:choose>
      <xsl:when test="Col[ValidationType='Task: Non-Numeric']">
        <td class="warningTd">
          <span class="warningRed">
            <xsl:value-of select="ColVal"/>
          </span>
        </td>
      </xsl:when>
      <xsl:when test="Col[count(ValidationType)=0]">
      <td class="warningTd">
        <span class="normal">
          <xsl:value-of select="ColVal"/>
        </span>
      </td>
    </xsl:when>
    </xsl:choose>
  </xsl:for-each>
</tr>
</xsl:for-each>

标签: htmlxmlxslt

解决方案


假设您只想在 a<RejRow>同时具有 a<ValidationType>和 a<Col><ColName>等于时输出 a Test2

<xsl:template match="/CurrentFile">
  <table>
    <xsl:for-each select="RejRow[Col[ValidationType and ColName='Test2']]">
      <tr>
        <xsl:for-each select="Col[ColName='Test2']">
          <td class="warningTd">
            <span>
              <xsl:attribute name="class">
                <xsl:choose>
                  <xsl:when test="ValidationType = 'Task: Non-Numeric'">warningRed</xsl:when>
                  <xsl:otherwise>normal</xsl:otherwise>
                </xsl:choose>
              </xsl:attribute>
              <xsl:value-of select="ColVal" />
            </span>
          </td>
        </xsl:for-each>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>

请注意,<td>如果有多个 ,这将创建多个Col[ColName='Test2']

输出是:

<table>
   <tr>
      <td class="warningTd">
         <span class="warningRed">TestVal2</span>
      </td>
   </tr>
</table>

推荐阅读