Condition in XSLT 1.0?

前端 未结 3 1489
半阙折子戏
半阙折子戏 2021-01-19 08:14

I have an XSLT 1.0 (2.0 is not an option) stylesheet which produces XHTML. It can, depending on a parameter, produce a full XHTML validable document or just a

相关标签:
3条回答
  • 2021-01-19 08:22

    It sounds like what you need is two different stylesheets. If at all possible you should create two separate stylesheets and dynamically call the one you need from code.

    0 讨论(0)
  • 2021-01-19 08:22

    Another option, which I recently had to employ, is to:

    1. Omit the XML declaration in all cases.
    2. Conditionally, output the declaration as unescaped text.

    This only works in XSLT 1.0 and 2.0 if you're outputting to a file -- this won't work if you need to process the output as XML in the same pass, such as when storing in a variable.

    (Note that XSLT 2.0 extension functions might make it possible to take this output and treat it as XML in one go, and XSLT 3.0 has a built-in function to parse an input string as XML.)

    Example snippet:

    <!-- 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 ] ...
    
    0 讨论(0)
  • 2021-01-19 08:26

    In XSLT the value of omit-xml-declaration must be either yes or no, you can't use Attribute Value Templates there. This applies to both 1.0 and 2.0.

    The doctype attributes can use AVTs, but the problem is that you cannot omit the attribute, you can only output an empty attribute and this leads to output that has empty doctype strings.

    Sorry, can't be done with XSLT. You can either use two different stylesheets, or set the output parameters in the code that calls the XSLT processor.

    0 讨论(0)
提交回复
热议问题