我正在使用xslt将xml文档转换为html表,现在我想要做的是更改包含最低“price”值的单元格的背景颜色,而不对列表进行排序. 我是新手,所以我正在做的是遵循W3C学校的例子. xml文件如下所
我是新手,所以我正在做的是遵循W3C学校的例子. xml文件如下所示:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Black angel</title>
<artist>Savage Rose</artist>
<country>EU</country>
<company>Mega</company>
<price>11.90</price>
<year>1995</year>
</cd>
<cd>
<title>For the good times</title>
<artist>Kenny Rogers</artist>
<country>UK</country>
<company>Mucik Master</company>
<price>8.70</price>
<year>1995</year>
</cd>
</catalog>
我想要获得的是类似于此但没有按价格排序列表中的元素.所以我想在XML文档中维护原始顺序.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
<th>Price</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:sort select="price" order="ascending" data-type="number"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<xsl:choose>
<xsl:when test="(position() = 1)">
<td bgcolor="#ff00ff">
<xsl:value-of select="price"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="price"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
在此先感谢您的帮助.
编辑:我想我找到了一个问题的解决方案:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
<th>Price</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<xsl:choose>
<xsl:when test="price=/catalog/cd/price[not(. > ../../cd/price)][1]">
<td bgcolor="#ff00ff">
<xsl:value-of select="price"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="price"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
你似乎已经回答了你的问题,但我会在这里提出其他一些事情.
(1)您可以避免通过< cd />重新计算每次迭代的最低价格.通过向样式表或模板添加变量来执行计算一次:
<xsl:variable name="least" select="math:min(/catalog/cd/price)"/>
(2)“$least”变量声明使用EXSLT数学:min函数(命名空间为xmlns:math =“http://exslt.org/math”),它可供您的XSLT 1.0处理器使用.如果您有2.0处理器,则可以使用内置的“min()”.
如果没有别的,min()函数对下一个人来说更具可读性.
(3)这是纯粹的风格,但你可以通过使用xsl:属性来减少分支.
<td>
<xsl:if test="price=$lowest">
<xsl:attribute name="bgcolor">#ff00ff</xsl:attribute>
</xsl:if>
<xsl:value-of select="price"/>
</td>
