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

使用XSLT将XML文件转换为HTML,是处理结构化数据并以网页形式展示的常用方法。整个过程不复杂,只需三步:准备XML源文件、编写XSLT样式表、执行转换。下面一步步说明如何操作。
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>
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>说明:
为了让浏览器自动执行转换,可以在XML文件顶部加入对XSLT的引用:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="books.xsl"?> <library> ... </library>
保存后,直接在浏览器中打开 books.xml,就能看到渲染后的HTML页面。
如果想在网页中动态转换,可以使用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>基本上就这些。只要XML结构清晰,XSLT写法规范,转换过程非常直观。你可以根据需要添加排序、条件判断(xsl:if)、链接等增强功能。
以上就是如何使用XSLT转换xml文件 将xml转换为html的详细教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号