比如,我們有這麼一個記錄網址的XML文檔:
<?XML version="1.0" encoding="utf-8" ?>
<?XML-stylesheet type="text/xsl" href="XSLTFileLlink.xsl" ?>
<items>
<roomitem>
<text>新浪</text>
<link>http://www.sina.com.cn</link>
</roomitem>
<roomitem>
<text>yahoo</text>
<link>http://www.yahoo.com</link>
</roomitem>
<roomitem>
<text>Google</text>
<link>http://www.google.com</link>
</roomitem>
<studyitem>
<text>Html簡易教程</text>
<link><a href="gohttp://www.shanxiwindow.Net/teaching/Htmlbook/">go</a></link>
</studyitem>
<studyitem>
<text>Javascript中文簡介</text>
<link>http://www.lib.tsinghua.edu.cn/chinese/INTERNET/JavaScript/</link>
</studyitem>
<studyitem>
<text>msdn中文站點</text>
<link>http://www.microsoft.com/china/msdn/default.mspx</link>
</studyitem>
<studyitem>
<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>