IanT8
IanT8

Reputation: 2217

How to stop unwanted whitespace appearing in output following Xslt transformation

I'm using VS2008 to write and test an xsl transformation. The output contains unwanted white space as illustrated by this simplified example:

Input:

<?xml version="1.0" encoding="utf-8" ?>
<envelope>
  <header>
    <head id="1" text="Heading1"/>
  </header>
  <body>
    <message>
      <items>
        <item id="1" Color="Red"/>
        <item id="2" Color="Green"/>
        <item id="3" Color="Blue"/>
        <item id="4" Color="Purple"/>
      </items>
    </message>
  </body>
</envelope>

Transformation:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="message">
    <xsl:element name="Colors">
      <xsl:apply-templates select="items/item" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="items/item">
    <xsl:element name="Color">
      <xsl:value-of select="@Color"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="utf-8"?>




        <Colors><Color>Red</Color><Color>Green</Color><Color>Blue</Color><Color>Purple</Color></Colors>

Whilst its difficult to show in the output, what seems to be happening is whitespace from the input file is being sent to the output file even when my template doesn't match. This is what I'd like and expect the output to look like:

<?xml version="1.0" encoding="utf-8"?>
<Colors>
  <Color>Red</Color>
  <Color>Green</Color>
  <Color>Blue</Color>
  <Color>Purple</Color>
</Colors>

Is this possible? What I may have to do now is to load the result into an Xml document, then write it out again formatted.

Upvotes: 0

Views: 858

Answers (1)

SingleShot
SingleShot

Reputation: 19131

To remove the unwanted whitespace, adding this template should do the trick:

<xsl:template match="text()"/>

It means "ignore all text nodes".

For the pretty-printing, the indent attribute on your output element should work. I'm not sure why it is being ignored and everything is on the same line. Perhaps a Microsoft issue?

Upvotes: 2

Related Questions