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="."/>
  </xsl:template>
</xsl:stylesheet>
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:stylesheet
  <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>
      <xsl:copy-of select="@*" />
      <xsl:apply-templates>
        <xsl:with-param name="indent" 
                select="concat($indent, $indent-increment)"/>
      </xsl:apply-templates>
      <xsl:if test="*">
        <xsl:value-of select="$indent"/>
      </xsl:if>
    </xsl:copy>
  </xsl:template>

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

</xsl:stylesheet>

Enter your comment

Name Email
URL
If you have an account, please log in.
No account? Just create one.


Jez Higgins