Karol Stojek
Karol Stojek

Reputation: 62

strip leading and trailing newline characters in xslt

I have a xml with structure like this:

<xxx>
<yyy>
some text   with spaces inside
</yyy>
<zzz>
another text
</zzz>
</xxx>

I want to generate html that will be formatted with white-space:pre style, but I must remove the newline characters from node yyy and zzz.

My output should be something like this:

<div><div>some text   with spaces inside</div><div>another text</div></div>

I've tried

<xsl:output method="html" indent="no"/>
<xsl:strip-space elements="*"/>

but it didn't work. The newline characters are still there.

I can't use normalize-space because the whitespaces between the words are important.

Upvotes: 1

Views: 5247

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

Because you only want to remove the first and last characters from the string, this simpler transformation does exactly this:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="yyy/text() | zzz/text()">
   <xsl:value-of select="substring(.,2, string-length() -2)"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<xxx>
<yyy>
some text   with spaces inside
</yyy>
<zzz>
another text
</zzz>
</xxx>

the wanted, correct result is produced:

<xxx>
<yyy>some text   with spaces inside</yyy>
<zzz>another text</zzz>
</xxx>

Do note: In a more complicated case you might want to strip-off all leading whitespace and all trailing witespace.

This can be done if you use the trim() function/template from FXSL:

Here is a demo of using trim():

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

  <xsl:import href="trim.xsl"/>

  <!-- to be applied on trim.xml -->

  <xsl:output method="text"/>
  <xsl:template match="/">
    '<xsl:call-template name="trim">
        <xsl:with-param name="pStr" select="string(/*)"/>
    </xsl:call-template>'
  </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<someText>

   This is    some text   

</someText>

the wanted (trimmed) result is produced:

'This is    some text'

Upvotes: 1

Lukasz
Lukasz

Reputation: 7662

The following XSL removes all newline characters from elements yyy and zzz:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:template match="/xxx">
<div>
    <xsl:apply-templates />
</div>
</xsl:template>
<xsl:template match="yyy | zzz">
<div>
    <xsl:value-of select="translate(.,'&#x0d;&#x0a;', '')" />
</div>  
</xsl:template>
</xsl:stylesheet>

Upvotes: 3

Related Questions