模板与匹配
XSLT 的核心机制:模板匹配。处理器从根节点开始,找到匹配的模板执行,apply-templates 把处理交给子节点。
模板规则
<xsl:template match="XPath"> 匹配什么节点;match="/" 匹配根;match="book" 匹配所有 book 元素。
处理流程
根模板执行 → apply-templates 选择子节点 → 每个子节点找匹配模板 → 递归下去。没有匹配模板的节点被忽略(文本和属性除外)。
代码示例
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- 根模板 -->
<xsl:template match="/">
<html>
<head><title>书目</title></head>
<body>
<xsl:apply-templates select="bookstore/book"/>
</body>
</html>
</xsl:template>
<!-- book 模板 -->
<xsl:template match="book">
<div class="book">
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="price"/>
</div>
</xsl:template>
<!-- title 模板 -->
<xsl:template match="title">
<h3><xsl:value-of select="."/></h3>
</xsl:template>
<xsl:template match="price">
<span>¥<xsl:value-of select="."/></span>
</xsl:template>
</xsl:stylesheet>