学习资源来自w3schoolXSLT 教程 (w3school.com.cn)https://www.w3school.com.cn/xsl/index.asp
-
<xsl:value-of> 元素用于提取某个选定节点的值,并把值添加到转换的输出流中:
<td><xsl:value-of select="catalog/cd/title"/></td>
select 属性的值是一个 XPath 表达式。此表达式的工作方式类似于定位某个文件系统,在其中正斜杠可选择子目录。
-
<xsl:for-each> 元素可用于选取指定的节点集中的每个 XML 元素。
<?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> <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> </table> </body> </html> </xsl:template> </xsl:stylesheet>
通过在 <xsl:for-each> 元素中添加一个选择属性的判别式,我们也可以过滤从 XML 文件输出的结果。<xsl:for-each select="catalog/cd[artist='Bob Dylan']"> 合法的过滤运算符:
= (等于)
!= (不等于)
< (小于)
> (大于) -
如需对结果进行排序,只要简单地在 XSL 文件中的 <xsl:for-each> 元素内部添加一个 <xsl:sort> 元素:
<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>
在 XSL 文件中的 <xsl:for-each> 元素内部添加 <xsl:if> 元素,必选的 test 属性的值包含了需要求值的表达式。:
<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>
上面的代码会输出价格高于 10 的 CD 的 title 和 artist 元素。
-
XSLT <xsl:choose> 元素用于结合 <xsl:when> 和 <xsl:otherwise> 来表达多重条件测试。
<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>
上面的代码会在 CD 的价格高于 10 时向 "Artist" 列添加粉色的背景颜色。 这是另外一个包含两个 <xsl:when> 元素的例子:
<xsl:choose> <xsl:when test="price > 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:when test="price > 9"> <td bgcolor="#cccccc"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose>
5、<xsl:apply-templates> 元素
<xsl:apply-templates> 元素可把一个模板应用于当前的元素或者当前元素的子节点。假如我们向 <xsl:apply-templates> 元素添加一个 select 属性,此元素就会仅仅处理与属性值匹配的子元素。我们可以使用 select 属性来规定子节点被处理的顺序。
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> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="cd"> <p> <xsl:apply-templates select="title"/> <xsl:apply-templates select="artist"/> </p> </xsl:template> <xsl:template match="title"> Title: <span style="color:#ff0000"> <xsl:value-of select="."/></span> <br /> </xsl:template> <xsl:template match="artist"> Artist: <span style="color:#00ff00"> <xsl:value-of select="."/></span> <br /> </xsl:template> </xsl:stylesheet>