Disable xsl:comment in XSLT transformation

249 views Asked by At

I have an XSLT file littered with comments such as the following:

<xsl:comment>Entering shipping block</xsl:comment>

Is there a way to explicity disable these comments so that they aren't output at runtime in production? The output of the XSLT file is shown in a public API, so while it is useful for debugging, I would rather be able to switch it off.

The only way I can think of is to have a flag that is set in development mode to turn on the comments:

<xsl:if test="$enableDebug='true'">
    <xsl:comment>Entering shipping block</xsl:comment>
</xsl:if>

Is there another way?

(I'm using XSLT 2.0.)

2

There are 2 answers

2
Kim Homann On

You could declare a variable verbose at the very top of your XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output encoding="UTF-8" indent="yes" method="xml"/>
    <xsl:variable name="verbose">1</xsl:variable>
    <xsl:template match="@*|node()">
        <xsl:copy>
        ...

and wrap your comments in <xsl:if> like this:

<xsl:if test="$verbose">
    <xsl:comment>Applying the template...</xsl:comment>
</xsl:if>

If you then want to temporarily deactivate the comments, just remove the 1 from the verbose variable:

<xsl:variable name="verbose"></xsl:variable>
0
Dimitre Novatchev On

Just include this transformation step in your deployment to production:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="comment()"/>
</xsl:stylesheet>

You my even not specify any indent attribute on <xsl:output> in case readability is not a goal.