4

我有一个生成 XHTML 的 XSLT 1.0(2.0 不是一个选项)样式表。根据参数,它可以生成完整的 XHTML 有效文档或只是一个<div>...</div>片段,用于包含在 Web 页面中。

我的问题是在这两种情况下产生不同的 XML 声明。对于独立页面,我需要:

<xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
       doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>

对于<div>一个:

<xsl:output omit-xml-declaration="yes"/>

<xsl:output>不能包含在<xsl:if>. 它只能是 的直接子代<xsl:stylesheet>

我看到的唯一解决方案是创建一个包含大多数模板的样式表,然后是两个小的“包装器”,右边<xsl:output><xsl:import>主样式表。

我一直在寻找更好的主意,但显然没有。根据 Andrew Hare 和 jelovirt 的建议,我编写了两个“驱动程序”,两个简单的样式表,分别调用正确<xsl:output>的样式表和主样式表。这是这些驱动程序之一,用于独立 HTML 的驱动程序:

<?xml version="1.0" encoding="us-ascii"?>
<!-- This file is intended to be used as the main stylesheet, it creates a 
 standalone Web page. 
-->
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

  <xsl:import href="traceroute2html.xsl"/>

  <xsl:param name="standalone" select="'true'"/>

  <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
      doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>

</xsl:stylesheet>
4

3 回答 3

2

我最近不得不采用的另一种选择是:

  1. 在所有情况下都省略 XML 声明。
  2. 有条件地,将声明输出为未转义的文本

这仅适用于 XSLT 1.0 和 2.0,如果您要输出到文件 - 如果您需要在同一通道中将输出作为 XML 处理,例如存储在变量中时,这将不起作用。

(请注意,XSLT 2.0 扩展函数可能可以一次性获取此输出并将其视为 XML,并且 XSLT 3.0 具有将输入字符串解析为 XML 的内置函数。)

示例片段:

<!-- Omit the XML declaration as the base case:
    we can conditionally output a declaration 
    as text, but we *cannot* apply conditions on
    this `omit-xml-declaration` attribute here.  -->
<xsl:output method="xml" indent="no" 
    omit-xml-declaration="yes"
/>

<!-- Root element match: evaluate different cases, output XML declaration,
    XHTML DOCTYPE, or something else, then process the rest of the input. -->
<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="'... some condition ...'">
            <xsl:text disable-output-escaping="yes">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</xsl:text>
        </xsl:when>
        <xsl:when test="'... some other condition ...'">
            <xsl:text disable-output-escaping="yes">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <!-- ... some third kind of output ... -->
        </xsl:otherwise>
    </xsl:choose>
    <!-- Just process the rest -->
    <xsl:apply-templates/>
</xsl:template>


... [ other code ] ...
于 2017-03-29T23:09:49.253 回答
1

听起来您需要的是两个不同的样式表。如果可能的话,您应该创建两个单独的样式表并从代码中动态调用您需要的样式表。

于 2009-03-11T10:40:31.450 回答
1

在 XSLT 中, 的值omit-xml-declaration必须是yesor no,您不能在那里使用属性值模板。这适用于 1.0 和 2.0。

doctype 属性可以使用 AVT,但问题是您不能省略该属性,您只能输出一个空属性,这会导致输出具有空的 doctype 字符串。

抱歉,不能用 XSLT 完成。您可以使用两个不同的样式表,也可以在调用 XSLT 处理器的代码中设置输出参数。

于 2009-03-12T06:43:41.463 回答