XSL代码
<?xml version="1.0" encoding="ISO-8859-1"?>
<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>
</tr>
<tr>
<td><xsl:value-of select="catalog/cd/title"/></td>
<td><xsl:value-of select="catalog/cd/artist"/></td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XML代码
<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>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
1.声明
由于 XSL 样式表本身也是一个 XML 文档,因此它总是由 XML 声明起始:
<?xml version="1.0" encoding="ISO-8859-1"?>
2.命名空间`
`定义此文档是一个 XSLT 样式表文档(连同版本号和 XSLT 命名空间属性)。例如:
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
3.定义模板
<xsl:template>
元素定义了一个模板。而 match=”/” 属性则把此模板与 XML 源文档的根相联系。
<xsl:template>
元素内部的内容定义了写到输出结果的 HTML 代码。
4.<xsl:value-of>
元素
a.<xsl:value-of>
元素用于提取某个选定节点的值,并把值添加到转换的输出流中。
b.select 属性的值是一个 XPath 表达式。此表达式的工作方式类似于定位某个文件系统,在其中正斜杠可选择子目录。
例如:
<td><xsl:value-of select="catalog/cd/title"/></td>
5.<xsl:for-each>
元素
a. <xsl:for-each>
元素可用于选取指定的节点集中的每个 XML 元素。
例如:
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
b.<xsl:for-each>
添加一个选择属性的判别式
合法的过滤运算符:
= (等于)
!= (不等于)
< (小于)
> (大于)
例如:过滤元素artist 元素等于a的代码如下:
<xsl:for-each select="catalog/cd[artist='a']">
c.<xsl:sort>
元素用于对结果进行排序
在 XSL 文件中的 <xsl:for-each>
元素内部添加一个 <xsl:sort>
元素:
对artist进行排序:
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
6.<xsl:if>
元素
<xsl:if test="expression">
...
...如果条件成立则输出...
...
</xsl:if>
例如:代码仅仅会输出价格高于 10 的 CD 的 title 和 artist 元素。
<xsl:for-each select="catalog/cd">
<xsl:if test="price > 10">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:if>
</xsl:for-each>
7.<xsl:choose>
元素
类似与switch语句
<xsl:choose>
<xsl:when test="expression">
... 输出 ...
</xsl:when>
<xsl:otherwise>
... 输出 ....
</xsl:otherwise>
</xsl:choose>
例如:代码会在 CD 的价格高于 10 时向 “Artist” 列添加粉色的背景颜色。
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="artist"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>