Comments allow you to hide advisory text in an XML document. You can also use comments to label documents, or portions of them, which can be useful for debugging. When an XML processor sees a comment, it may ignore or discard it, or it can make the text content of comments available for other kinds of processing. The text in comments is not the same as the text found between element tags, that is, it is not character data. As such, comments can contain characters that are otherwise forbidden, like < and &. XML comments are formed like this: <!-- This element holds the current date & time -->
The only legal XML characters that a comment must not contain are the sequence of two hyphen characters (--), as this pair of characters signals the end of a comment. Other than that, you are free to use any legal XML character in a comment. (Again, to check on what characters are legal in XML, and where they are legal, see Sections 2.2 through 2.4 of the XML specification.) To insert a comment into a result tree, you can use the XSLT instruction element comment, as demonstrated in the comment.xsl stylesheet: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:comment> comment & msg element </xsl:comment> <msg><xsl:apply-templates/></msg> </xsl:template> </xsl:stylesheet> The output method is XML. If it were text, the comment would not show up in the output. Because comments in XML can contain markup characters, you can include an ampersand in a comment, among otherwise naughty characters, though it must first be represented by an entity reference (&) in the stylesheet. Process this stylesheet against comment.xml with Xalan: xalan comment.xml comment.xsl You will get the following results: <?xml version="1.0" encoding="UTF-8"?> <!-- comment & msg element --> <msg>You can insert comments in your output.</msg> |