使用XSLT将XML转换为HTML需三步:准备XML数据文件,编写定义转换规则的XSLT样式表,通过浏览器或JavaScript执行转换并展示结果。

使用XSLT将XML文件转换为HTML,是处理结构化数据并以网页形式展示的常用方法。整个过程不复杂,只需三步:准备XML源文件、编写XSLT样式表、执行转换。下面一步步说明如何操作。
1. 准备XML文件
XML文件用于存储数据,结构清晰。例如,有一个名为 books.xml 的文件:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1">
<title>JavaScript高级程序设计</title>
<author>Nicholas C. Zakas</author>
<price>89.00</price>
</book>
<book id="2">
<title>你不知道的JavaScript</title>
<author>Kyle Simpson</author>
<price>65.50</price>
</book>
</library>
2. 编写XSLT样式表
XSLT文件定义了如何将XML转换为HTML。创建一个名为 books.xsl 的文件,并添加以下内容:
立即学习“前端免费学习笔记(深入)”;
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<p><!-- 输出格式设为HTML -->
<xsl:output method="html" indent="yes"/></p><p><!-- 匹配根元素 -->
<xsl:template match="/library">
<html>
<head>
<title>图书列表</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
th { background-color: #f4f4f4; }
</style>
</head>
<body>
<h1>我的图书库</h1>
<table>
<tr>
<th>ID</th>
<th>书名</th>
<th>作者</th>
<th>价格(元)</th>
</tr>
<!-- 遍历每本书 -->
<xsl:for-each select="book">
<tr>
<td><xsl:value-of select="@id"/></td>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template></p><p></xsl:stylesheet></p>说明:
- xsl:output 指定输出为HTML格式。
- xsl:template match="/library" 表示从根节点开始匹配。
- xsl:for-each 用于遍历每个 book 元素。
- xsl:value-of 提取元素或属性的值。
3. 在XML中引用XSLT
为了让浏览器自动执行转换,可以在XML文件顶部加入对XSLT的引用:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="books.xsl"?> <library> ... </library>
保存后,直接在浏览器中打开 books.xml,就能看到渲染后的HTML页面。
4. 使用JavaScript手动转换(可选)
如果想在网页中动态转换,可以使用JavaScript:
<script>
async function transformXML() {
const xsltProcessor = new XSLTProcessor();
const xslReq = await fetch('books.xsl');
const xslDoc = await xslReq.text();
const parser = new DOMParser();
const xslDOM = parser.parseFromString(xslDoc, 'text/xml');
<p>xsltProcessor.importStylesheet(xslDOM);</p><p>const xmlReq = await fetch('books.xml');
const xmlDocText = await xmlReq.text();
const xmlDoc = parser.parseFromString(xmlDocText, 'text/xml');</p><p>const result = xsltProcessor.transformToFragment(xmlDoc, document);
document.getElementById('output').appendChild(result);
}
</script></p><p><div id="output"></div>
<script>transformXML();</script></p>5. 注意事项
- 确保XML和XSLT文件编码一致(推荐UTF-8)。
- XSLT 1.0 是最广泛支持的版本,适合大多数场景。
- 浏览器中调试时,建议使用Chrome或Firefox查看控制台错误。
- 若样式未生效,检查路径是否正确,或尝试绝对路径。
基本上就这些。只要XML结构清晰,XSLT写法规范,转换过程非常直观。你可以根据需要添加排序、条件判断(xsl:if)、链接等增强功能。










