xml 在网络上经常可以看到背景色按行交替设置的表格,比较美观。但未必需要什么高深的服务器技术,用简单的xsl+xml照样能很好的实现他们。
比如,我们有这么一个记录网址的xml文档:
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl"
<text>Microsoft .Net 框架 SDK 快速入门教程</text>
<link>http://chs.gotdotnet.com/quickstart/default.aspx</link>
</studyitem>
</items>
现在,我希望按照其分类,把他表现成两个颜色按行交替的表格。如下图所示:
Xsl可以如此写出,
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<!--
This is an XSLT template file. Fill in this area with the
XSL elements which will transform your XML to XHTML.
-->
<h1>XSLT应用测试</h1>
<hr />
<h3>功能类:</h3>
<table width="100%" border="1">
<tr bgcolor="#C9BBAD">
<th>name</th>
<th>link</th>
</tr>
<xsl:for-each select="items/roomitem">
<xsl:choose>
<xsl:when test="(position() mod 2) = 0">
<tr bgcolor="#C9BBAD">
<td>
<xsl:value-of select="text" />
</td>
<td>
<xsl:value-of select="link" />
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td>
<xsl:value-of select="text" />
</td>
<td>
<xsl:value-of select="link" />
</td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</table>
<br />
<h3>资源类:</h3>
<table width="100%" border="1">
<tr bgcolor="#C9BBAD">
<th>name</th>
<th>link</th>
</tr>
<xsl:for-each select="items/studyitem">
<xsl:choose>
<xsl:when test="(position() mod 2) = 0">
<tr bgcolor="#C9BBAD">
<td>
<xsl:value-of select="text" />
</td>
<td>
<xsl:value-of select="link" />
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td>
<xsl:value-of select="text" />
</td>
<td>
<xsl:value-of select="link" />
</td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>