我正在使用XSLT,需要根据参数在转换后的输出中动态生成doctype.我听说使用XSLT 1.0无法做到这一点,但使用结果文档标签可以使用版本2.0 .
到目前为止,从这个问题的答案,我有这样的事情:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" indent="yes"/>
<xsl:param name="doctype.system" select="'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'" />
<xsl:param name="doctype.public" select="'-//W3C//DTD XHTML 1.0 Strict//EN'" />
<xsl:template match="/">
<xsl:result-document doctype-public="{$doctype.public}" doctype-system="{$doctype.system}" method="html">
<html>
<head>
<xsl:apply-templates select="report/head/node()"/>
</head>
<body>
<!-- ommitted for brevity -->
</body>
</html>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
上面的问题是没有产生输出!
如果我从上面删除结果文档标记,则应用我的转换并按预期输出文档.
有线索吗?我正确使用结果文档标签吗?
更新:回应这里的一些评论是一个有效的小版本,一个没有的版本(省略结果文档指令的参数化)
这有效(没有结果文件):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html>
<head>
</head>
<body>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输出:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body></body>
</html>
Run Code Online (Sandbox Code Playgroud)
但这不会产生任何输出:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<xsl:result-document doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" method="html">
<html>
<head>
</head>
<body>
</body>
</html>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
正如您也发现的那样,Xalan仅支持XSLT 1.0,但如果您已经改为Saxon 9,则可以轻松实现您想要的效果.
此外,您可以xsl:output
使用名称定义一个名称并将其用作以下格式的格式,而不是使用您的文档类型设置定义参数xsl:result-document
:
<xsl:output name="my-xhtml-output" method="xml" encoding="UTF-8" indent="yes"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>
Run Code Online (Sandbox Code Playgroud)
在你的xsl:result-document
身上然后使用这个输出格式:
<xsl:result-document href="{$filename}" format="my-xhtml-output">
...
</xsl:result-document>
Run Code Online (Sandbox Code Playgroud)
Imo,如果你有很多输出格式,它可以更容易地维护不同的输出格式.