NestorDRod
NestorDRod

Reputation: 166

Controlling whitespace/newlines in XSLT output

I've been searching through the questions to see if this particular one's been answered with no success. If I simply missed it, my apologies.

I have the need to "flatten" individual XML nodes so that they are output as a single line. Whitespace between the nodes is not needed, and newlines within text nodes are tobe replaced by a special character ('\n').

An example XML:

<events>
  <event>
    <id>123</id>
    <type>read</type>
    <description>
      some text here
    </description>
  </event>
</events>

What I'd like as output is:

<events>
<event><id>123</id><type>read</type><description>\nsome text here\n</description></event>
</events>

I tried using the <xsl:strip-space> tag, and that takes care of the whitespace between the tags, but doesn't touch the newlines in side the element.

I tried adding the following template:

<xsl:template match="text()">
  <xsl:copy-of select="translate(.,'&#xA;','\n')"/>
</xsl:template>

but that seems to remove all the tags and just output the text.

Help?

Upvotes: 1

Views: 851

Answers (1)

kjhughes
kjhughes

Reputation: 111601

Your sample XML input document:

<events>
  <event>
    <id>123</id>
    <type>read</type>
    <description>
      some text here
    </description>
  </event>
</events>

Given to this XSLT 2.0 transformation:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" indent="no" omit-xml-declaration="yes"/>

  <xsl:template match="*|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="replace(., '[ \t\r]*\n[ \t\r]*', '\\n')"/>
  </xsl:template>

</xsl:stylesheet>

Produces your requested XML output document:

<events><event><id>123</id><type>read</type><description>\nsome text here\n</description></event></events>

Upvotes: 4

Related Questions