0
嘗試按照Martin Fowler所述實現模式「Two Step View」時,出現了使HTML表格的備用行着色生效的問題。這使用XSLT position()
函數。您可以在下面看到table/row
的XSLT模板。但是,在輸出中,tr
元素的bgcolor
屬性始終爲"linen"
,表明position()
的值在我們遍歷table/row
元素時未發生變化。爲什麼會這樣?XSLT position()函數在兩步驟視圖中未按預期工作
<?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>
謝謝,這工作。但是,我不明白爲什麼,'會阻止'position()'測試對非行元素進行評估? 'match'(不起作用)和'select ='(它起作用)之間有什麼區別? –
amoe
使用' '(因爲它是'''的縮寫),您可以選擇所有的子節點進行處理,與'相比,正在處理不同的節點集(XSLT 1.0)或序列(XSLT 2.0)。在所有子節點內,與僅查看「row」元素相比,特定的「row」元素具有不同的位置,特別是在元素節點之間存在空白文本節點的格式化XML的情況下。有關詳細信息,請參閱https://www.w3.org/TR/xslt#section-Applying-Template-Rules。 –
分別https://www.w3.org/TR/xslt20/#applying-templates說:「匹配排序序列中的第N個節點的規則與該節點一起作爲上下文項目評估,N作爲上下文位置,並將排序序列的長度作爲上下文大小。「 –