Indenting an XML File using an XSL Transformation

It is sometimes useful to generated indented Xml files. This article show an example of how to do this easily, using the "Xslt Transformation" action.

Xml indentation is a visual cumfort when viewing files, but:
- Indentation produces bigger files, which may lead to performance loss
- Some third party applications may behave differently depending on Xml file indentation
- For these reasons, we recommend not to indent files in Production unless it is required

The Xml file

The Xml file is a simple export of customer data, from our demo database.

411 mappingxml

Here is a sample result:

<?xml version="1.0" encoding="UTF-8"?><customers xmlns:xs="http://www.w3.org/2001/XMLSchema"><person><id>1</id><firstname>Jason</firstname><lastname>GIBBS</lastname><fullname>Jason GIBBS</fullname></person><person><id>2</id><firstname>Michael</firstname><lastname>O’NEAL</lastname><fullname>Michael O’NEAL</fullname></person><person><id>3</id><firstname>Tony</firstname><lastname>JIMENEZ</lastname><fullname>Tony JIMENEZ</fullname></person></customers>

Now let’s see how we can indent this.

Using an "identity" Xsl Transformation

Xsl transformations can be used to convert Xml files to other Xml structures or to other data formats.

In this example we do not want to alter the Xml structure, so we are going to use an "identity" transformation.

xDI Designer lets you apply Xsl Transformations through the "Xslt Transformation" palette action.

411 main

Here is the Xsl Transformation we specified in the action’s Expression Editor:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="no" indent="yes"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

Our sample result, indented:

<?xml version="1.0" encoding="UTF-8"?>
<customers xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <person>
      <id>1</id>
      <firstname>Jason</firstname>
      <lastname>GIBBS</lastname>
      <fullname>Jason GIBBS</fullname>
   </person>
   <person>
      <id>2</id>
      <firstname>Michael</firstname>
      <lastname>O'NEAL</lastname>
      <fullname>Michael O'NEAL</fullname>
   </person>
   <person>
      <id>3</id>
      <firstname>Tony</firstname>
      <lastname>JIMENEZ</lastname>
      <fullname>Tony JIMENEZ</fullname>
   </person>
</customers>