0

在尝试实现 Martin Fowler 所描述的模式“两步视图”时,我在让 HTML 表的交替行着色工作时遇到了一些问题。这使用 XSLTposition()函数。您可以在下面看到 XSLT 模板table/row。但是,在输出中,元素的bgcolor属性tr始终为"linen",表明 的值position()不会随着我们迭代table/row元素而改变。为什么会这样?

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="screen">
    <html>
      <body bgcolor="white">
        <xsl:apply-templates/>
      </body>
    </html>
  </xsl:template>

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

  <xsl:template match="field">
    <p><b><xsl:value-of select="@label"/>: </b><xsl:apply-templates/></p>
  </xsl:template>

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

  <xsl:template match="table/row">
    <xsl:variable name="bgcolor">
      <xsl:choose>
        <xsl:when test="(position() mod 2) = 0">linen</xsl:when>
        <xsl:otherwise>white</xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <tr bgcolor="{$bgcolor}"><xsl:apply-templates/></tr>
  </xsl:template>

  <xsl:template match="table/row/cell">
    <td><xsl:apply-templates/></td>
  </xsl:template>
</xsl:stylesheet>

输入 XML:

<?xml version="1.0"?>
<screen>
  <title>Dissociation</title>
  <field label="Artist">Dillinger Escape Plan</field>
  <table>
    <row>
      <cell>Limerent Death</cell>
      <cell>4:06</cell>
    </row>
    <row>
      <cell>Symptom Of Terminal Illness</cell>
      <cell>4:03</cell>
    </row>
    <row>
      <cell>Wanting Not So Much To As To</cell>
      <cell>5:23</cell>
    </row>
  </table>
</screen>

输出 HTML:

<html><body bgcolor="white">
  <h1>Dissociation</h1>
  <p><b>Artist: </b>Dillinger Escape Plan</p>
  <table>
    <tr bgcolor="linen">
      <td>Limerent Death</td>
      <td>4:06</td>
    </tr>
    <tr bgcolor="linen">
      <td>Symptom Of Terminal Illness</td>
      <td>4:03</td>
    </tr>
    <tr bgcolor="linen">
      <td>Wanting Not So Much To As To</td>
      <td>5:23</td>
    </tr>
  </table>
</body></html>
4

1 回答 1

1

更改<table><xsl:apply-templates/></table><table><xsl:apply-templates select="row"/></table>或使用<xsl:strip-space elements="*"/>或至少<xsl:strip-space elements="table"/>。目前您正在处理所有子节点,包括空白文本节点,这样您的尝试使用position()失败。

于 2017-01-30T17:39:58.780 回答