developer.</db:para>
</db:section>
<db:section>
<db:title>How do I learn the difference?</db:title>
<db:para>Interestingly enough, you can code the XSLT algorithm
in XSLT... one cool way to experiment with the
difference.</db:para>
</db:section>
</db:article>
清单 2. 转换成 HTML 的简单样式表
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:db="http://ananas.org/2002/docbook/subset">
<xsl:output method="html"/>
<xsl:template match="db:article">
<html>
<head><title>
<xsl:value-of select="db:articleinfo/db:title"/>
</title></head>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="db:para">
<p><xsl:apply-templates/></p>
</xsl:template>
<xsl:template match="db:ulink">
<a href="{@url}"><xsl:apply-templates/></a>
</xsl:template>
<xsl:template match="db:article/db:title">
<h1><xsl:apply-templates/></h1>
</xsl:template>
<xsl:template match="db:title">
<h2><xsl:apply-templates/></h2>
</xsl:template>
<xsl:template match="db:emphasis[@role='bold']">
<b><xsl:apply-templates/></b>
</xsl:template>
<xsl:template match="db:emphasis">
<i><xsl:apply-templates/></i>
</xsl:template>
</xsl:stylesheet>
图 1. 处理程序所看到的 XML 文档

遍历算法
这一节的目标是改写 清单 2,更加清楚地显示深度优先遍历算法。为此您需要一个命名模板。如果不熟悉命名模板,它们就相当于 XSLT 中的方法调用:命名模板是带有 name 属性的模板。它通过 xsl:param 指令接受参数,像下面这样:
<xsl:template name="print">
<xsl:param name="message"/>
<!-- template content goes here -->
</xsl:template>
xsl:call-template 指令用于调用命名模板(而不是 xsl:apply-templates ),比如:
<xsl:call-template name="print">
<xsl:with-param name="message"
select="'See if it prints this message.'"/>
</xsl:call-template>
清单 3是对 清单 2 的改写,它使得树的遍历算法更明显。为了避免依靠处理程序操作树,这个样式表有一个命名模板 main 实现了树的遍历。 main 是一个递归函数,它用 current 参数接受一个节点集并遍历该节点集。模板的主要部分是一条 choose 指令,为给定的节点寻找最适当的规则。在处理一个节点时,该模板递归地调用自身,以便处理该节点的孩子。
清单 3. 公开遍历算法的样式表
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:db="http://ananas.org/2002/docbook/subset">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:call-template name="main">
<xsl:with-param name="nodes" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template name="main">
<xsl:param name="nodes"/>
<xsl:for-each select="$nodes">
<xsl:choose>
上一篇:用XSLT进行WSDL处理
下一篇:使用Java和XSLT生成动态Web页面






