【发布时间】:2021-04-22 05:22:02
【问题描述】:
我正准备自动生成大约 2.500 行 XHTML,并使用 XSLT 将 XML/XSL 转换为输出 XHTML 文件。由于篇幅较长(也为了获得更好的概览),我希望将 XSL 模块化。
根据 XSL2.0 规范:https://www.w3.org/TR/xslt20/#include,我必须包含一个顶级元素,这意味着我不能在另一个模板中添加包含标记。
澄清我的问题:
在这种特定情况下,是否可以使用“xsl:include”作为构建 HTML 标记结构的一部分,其中 HTML 是父级,头部和主体是子级等?
注意!我完全意识到在执行“包含”方案时我缺少 HTML 标记, 但那是因为我不知道如何添加HTML标签以解决HTML结构。
我在 XSL 规范、Saxon 文档以及其他渠道中搜索了执行 XSLT 的示例,以及“xsl:include”以模块化代码,但没有成功。
XML 文件(用于两种测试场景):
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xml" href="stylesheet.xsl" version="2.0"?>
<data>
<repo-1>
<title>Title-1</title>
<title>Title-2</title>
</repo-1>
<repo-2>
<body>Body content from XML data</body>
</repo-2>
</data>
仅使用一个没有包含的 XSL 时的 XSL 文件
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data">
<html>
<head>
<title>
<xsl:value-of select = "repo-1/title[2]"/>
</title>
</head>
<body>
<xsl:value-of select = "repo-2/body"/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我的带有包含的 XSL
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Includes -->
<xsl:include href="head.xsl"></xsl:include>
<xsl:include href="body.xsl"></xsl:include>
样式表>
XSL 包含文件 [head]
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data/repo-1">
<head>
<title>
<xsl:value-of select = "title"/>
</title>
</head>
</xsl:template>
</xsl:stylesheet>
XSL 包含文件 [正文]
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data/repo-2">
<body>
<xsl:value-of select = "body"/>
</body>
</xsl:template>
</xsl:stylesheet>
使用一个 XSL 文件的结果:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title-2</title>
</head>
<body>Body content from XML data</body>
使用结果包括:
<?xml version="1.0" encoding="UTF-8"?>
<head>
<title>Title-1 Title-2</title>
</head>
<body>Body content from XML data</body>
</html>
使用包含的想要的结果
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title-2</title>
</head>
<body>Body content from XML data</body>
【问题讨论】:
-
<xsl:include>只是一条允许您将样式表模块合并在一起的指令。您的问题来自嵌套在/data/repo-1中的两个<title>元素,因此使用<xsl:value-of select = "title[2]"/>应该可以解决您的问题。请注意,在生成 HTML 时,请考虑在样式表的开头添加<xsl:output method="xhtml"/>。
标签: xml xslt xslt-1.0 xslt-2.0 xslt-3.0