Kirk Strobeck
Kirk Strobeck

Reputation: 18589

How to comment in XSLT and not HTML

I'm writing XSL and I want to make comments throughout the code that will be stripped when it's processed, like PHP, however I'm not sure how.

I'm aware of the comment object, but it prints out an HTML comment when processed. :\

<xsl:comment>comment</xsl:comment>

Upvotes: 54

Views: 76043

Answers (5)

Faris Kapo
Faris Kapo

Reputation: 366

This is the way to do it in order to create a comment node that won't be displayed in html

<xsl:comment>

  <!-- Content:template -->

</xsl:comment>

Upvotes: 1

Peter Brand
Peter Brand

Reputation: 624

Note that white space on either side of the comments can end up in the output stream, depending on your XSLT processor and its settings for handling white-space. If this is an issue for your output, make sure the comment is bracketed by xslt tags.

EG

<xsl:for-each select="someTag">
  <xsl:text>"</xsl:text>
    <!-- output the id -->
<xsl:value-of select="@id"/>
<xsl:text>"</xsl:text>
</xsl:for-each>

Will output " someTagID" (the indent tab/spaces in front of the comment tag are output). To remove, either unindent it flush with left margin, or bracket it like

<xsl:text>"</xsl:text><!-- output the id --><xsl:value-of select="@id"/>

Upvotes: 4

Veloz
Veloz

Reputation: 639

Just make sure that you put your <!-- comments --> AFTER the opening XML declaration (if you use one, which you really don't need):

BREAKS:

<!-- a comment -->
<?xml version="1.0"?>

WORKS:

<?xml version="1.0"?>
<!-- a comment -->

I scratched my head on this same issue for a bit while debugging someone else's XSLT... seems obvious, but easily overlooked.

Upvotes: 16

code master
code master

Reputation: 2026

Sure. Read http://www.w3.org/TR/xslt#built-in-rule and then it should be apparent why this simple stylesheet will (well, should) do what you want:

<?xml version="1.0"?>
<xsl:stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="comment()">
  <xsl:copy/>
</xsl:template>

<xsl:template match="text()|@*"/>

</xsl:stylesheet>

Try :

<xsl:template match="/">
  <xsl:for-each select="//comment()">
   <SRC_COMMENT>
   <xsl:value-of select="."/>
   </SRC_COMMENT>
  </xsl:for-each>
 </xsl:template>
or use a <xsl:comment ...> instruction for a more literal duplication of the source     document content in place of my <SRC_COMMENT> tag.

Upvotes: -1

Kathy Van Stone
Kathy Van Stone

Reputation: 26271

You use standard XML comments:

<!-- Comment -->

These are not processed by the XSLT transformer.

Upvotes: 109

Related Questions