Re: [xsl] How to get comments to indent on their own line in XML output?

Subject: Re: [xsl] How to get comments to indent on their own line in XML output?
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Tue, 08 Jul 2008 09:43:37 -0400
Alan,

At 02:51 AM 7/8/2008, you wrote:
What interests me is the least inelegant way of doing this "by hand", as you mention.

Elegance is certainly in the eye of the beholder, but you could generalize your creation of any comment like so:


<xsl:template name="make-comment">
  <xsl:param name="content" select="''"/>
  <xsl:text>&#xA;</xsl:text>
  <xsl:comment>
    <xsl:value-of select="$content"/>
  </xsl:comment>
  <xsl:text>&#xA;</xsl:text>
</xsl:template>

Then calling it like so:

<xsl:call-template name="make-comment">
  <xsl:with-param name="content">
    <xsl:apply-templates/>
  </xsl:with-param>
</xsl:call-template>

will result in a comment containing the string value of the results of applying templates to the context node (where the 'make-comment' template is called), preceded and followed by a CR character.

Of course, you can pass anything in as the parameter, and its string value will appear in the comment.

Indenting the comment is a bit trickier, but you might find that an indent based on the depth of the context node (where the comment is called) will work for you:

<xsl:template name="make-comment">
  <xsl:param name="content" select="''"/>
  <xsl:text>&#xA;</xsl:text>
  <xsl:for-each select="ancestor::*">
    <xsl:text>  </xsl:text>
  </xsl:for-each>
  <xsl:comment>
    <xsl:value-of select="$content"/>
  </xsl:comment>
  <xsl:text>&#xA;</xsl:text>
</xsl:template>

Adjustments may have to be made. In certain cases you may also find you have to pass the indent in as a parameter as well. It all depends on what your requirements are.

Note that in a system with many stylesheets under maintenance, it may also make sense to separate all this logic out into a post-processing stylesheet.

Cheers,
Wendell


====================================================================== Wendell Piez mailto:wapiez@xxxxxxxxxxxxxxxx Mulberry Technologies, Inc. http://www.mulberrytech.com 17 West Jefferson Street Direct Phone: 301/315-9635 Suite 207 Phone: 301/315-9631 Rockville, MD 20850 Fax: 301/315-8285 ---------------------------------------------------------------------- Mulberry Technologies: A Consultancy Specializing in SGML and XML ======================================================================

Current Thread