Jez Higgins

Freelance software grandad
software created
extended or repaired


Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed

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>


Tagged code, xml, and xslt


Jez Higgins

Freelance software grandad
software created
extended or repaired

Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed