<xsl:value-of select="city" />
<xsl:text>, </xsl:text>
<xsl:value-of select="state" />
<xsl:text> </xsl:text>
<xsl:value-of select="zip" />
</p>
<table>
<tr>
<th>description</th>
<th>cost</th>
</tr>
<xsl:for-each select="item">
<tr>
<td><xsl:value-of select="description" /></td>
<td><xsl:value-of select="totalcost" /></td>
</tr>
</xsl:for-each>
</table>
<p />
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
在这种形式的样式表中,您只有一个模板,它对应于您正在尝试检索的信息的根。嵌在源文档中的嵌套信息是通过使用 xsl:for-each 元素处理当前特定类型的节点的所有子节点来检索的。正如您可看到的那样,这种样式表非常易于读取。它比推形式的样式表短,其布局与期望的输出文档布局非常接近。当用拉形式编码时,只要采用期望的输出样本,将其添加到顶级模板。然后,可以用适当的代码替换该样本中的值来检索源文档的值。
因此,拉总是比推好,对吗?
尽管拉格式的确优于推格式(可读性、简洁且易于读取的布局),但您还是应该根据源文档的特征来选择样式表。请查看下面的结构示例,它包含描述一个虚构医疗过程的叙述:
清单 5. 样本叙述文档
<surgerylog>
<narrative>
<section time="13:00:00">first, the surgeon used the <tool>3-inch
scalpel</tool> to make a <procedure>two-inch incision</procedure>
in the patient's <location>lower left abdomen</location>.
<procedure>cautery</procedure> was then applied to the
<target>severed blood vessels</target> to stop the
bleeding.</section>
<section time="13:14:23">the surgeon then <procedure>cleaned and
dressed the incision</procedure>, using <tool>four two-by-two
sterile gauze pads</tool> and <tool>medium sutures</tool>.</section>
</narrative>
</surgerylog>
在这个叙述中,信息可能会以任何次序出现。文档中的一行可能有两条 tool 子句,后面跟了一条 procedure 子句,或者三条 location 子句。假设您想要产生与下面相似的输出:
清单 6. 样本叙述输出
<html>
<body>
<h1>surgery log</h1>
<p><b>13:00:00</b></p>
<p>first, the surgeon used the <i>3-inch scalpel</i> to make a
<font color="#ff8800">two-inch incision</font> in the patient's
lower left abdomen. <font color="#ff8800">cautery</font> was
then applied to the severed blood vessels to stop the bleeding.</p>
<p><b>13:14:23</b></p>
<p>the surgeon then <font color="#ff8800">cleaned and dressed
the incision</font>, using <i>four two-by-two sterile gauze pads</i>
and <i>medium sutures</i>.
</body>
</html>
有关样式表推格式的一件很重要的事,就是信息的出现次序是没有关系的。下面的样式表将清单 5 中的源 xml 处理成期望的 xhtml:
清单 7. 叙述的样本推样式表
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform"
version="1.0">
<xsl:template match="surgerylog/narrative">
<html>
<body>