Home > Uncategorized > XML indentation in XSLT

XML indentation in XSLT

This my first XSLT script. I usually use DOM (either Java or Python API) for such things but I wanted to give XSLT a try.

<?xml version="1.0" encoding="ISO-8859-15"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml"/>

  <xsl:template match="@*">
    <xsl:copy/>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="normalize-space(.)" />
  </xsl:template>

  <xsl:template match="*">
    <xsl:param name="indent" select="''"/>
    <xsl:text>&#xa;</xsl:text>
    <xsl:value-of select="$indent" />
    <xsl:copy>
      <xsl:apply-templates select="@*|*|text()">
        <xsl:with-param name="indent" select="concat($indent, '  ')"/>
      </xsl:apply-templates>
    </xsl:copy>
    <xsl:if test="count(../*)>0 and ../*[last()]=.">
      <xsl:text>&#xa;</xsl:text>
      <xsl:value-of select="substring($indent,3)" />
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>
Advertisements
Tags: ,
  1. Humberto
    June 8, 2011 at 19:25

    Excellent!!

    Works flawlessly

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: