How do I comment out an XML section that has comments inside?
You shouldn't do it, I know. Per the XML specification you aren't supposed to.
Having said that... I really needed it badly, so here's the trick. Surround the section you want to comment with an unused processing instruction:
<some-tags /><?comment <!-- traditional comment 1 --> <badtag prop1="123"> <!-- traditional comment 2 --> </badtag> <!-- traditional comment 3 -->?><rest-of-my-tags />
You can use any processing instruction that's not in use. I chose "comment" as the unused processing instruction, so I started the big comment with <?comment
and ended it with ?>
.
Pretty much any word will do as a processing instruction, since they aren't really used most of the time. I mean, when was the last time you used one?
--
is not allowed in XML comments. You can add a space between the two -
. If you want to do that programmatically, an XSLT may do the job for you. For example, the following XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:template match="/"> <a> <xsl:comment select="'a -- b -- c'"/> </a> </xsl:template></xsl:stylesheet>
Gives the following output:
<a><!--a - - b - - c--></a>
But the XSLT processor may also output an error. Given the specification, it's up to the implementation to add a space or raise an error.