实战案例
综合实战:把产品 XML 转成完整 HTML 页面。数据源 + 样式表 + 输出三步,这是 XSLT 最经典的应用场景。
功能
产品列表(含图片、名称、价格、标签)→ 页面 + 分类统计 + 价格筛选。整套转换逻辑都在 XSL 文件里。
代码示例
<?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>
<style>
.product { border: 1px solid #ddd; padding: 12px; margin: 8px;
border-radius: 8px; display: inline-block; }
.price { color: #e53935; font-weight: bold; }
.sale { background: #fff8e1; }
</style>
</head>
<body>
<h1>全部产品(<xsl:value-of select="count(catalog/product)"/> 件)</h1>
<xsl:for-each select="catalog/product">
<xsl:sort select="price" data-type="number"/>
<div class="product">
<xsl:if test="@on_sale = 'true'">
<xsl:attribute name="class">product sale</xsl:attribute>
</xsl:if>
<h3><xsl:value-of select="name"/></h3>
<p class="price">¥<xsl:value-of select="price"/></p>
<p><xsl:value-of select="desc"/></p>
<xsl:if test="@on_sale = 'true'">
<b>特价中</b>
</xsl:if>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>