2006-09-27  XSLT Scrapbook: Pretty Printing

Pretty printing XML looks like something that should be trivial in XSLT. Something like

<xsl:stylesheet ...>
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <xsl:copy-of select="."/>
perhaps? Sadly that only seems to work with Saxon.

Here's a more general solution, cooked up from suggestions here. It produces identical results for the transformers I tested - Saxon, Saxon8, Xalan and MSXML.

  <xsl:output method="xml" indent="no"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="indent-increment" select="'  '" />

  <xsl:template match="*">
    <xsl:param name="indent" select="'&#xA;'"/>

    <xsl:value-of select="$indent"/>
      <xsl:copy-of select="@*" />
        <xsl:with-param name="indent" 
                select="concat($indent, $indent-increment)"/>
      <xsl:if test="*">
        <xsl:value-of select="$indent"/>

  <xsl:template match="comment()|processing-instruction()">


[Add a comment]

Jez Higgins