Stephan
Stephan

Reputation: 43053

How to strip away carriage returns with XSLT only?

I have a xml code that can ahve two forms :

Form 1

<?xml version="1.0">
<info>
</info>

Form 2

<?xml version="1.0">
<info>
  <a href="http://server.com/foo">bar</a>
  <a href="http://server.com/foo">bar</a>
</info>

From a loop I read each form of xml and pass it to an xslt stylesheet.

XSLT code

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

    <xsl:template match="*|@*|text()">
       <xsl:apply-templates select="/info/a"/>
    </xsl:template> 

    <xsl:template match="a">
       <xsl:value-of select="concat(text(), ' ', @href)"/>
       <xsl:text>&#13;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

And I obtain this :


bar http://server.com/foo
bar http://server.com/foo

How can i remove the first empty line with XSLT only ?

Upvotes: 5

Views: 11793

Answers (3)

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

From a loop I read each form of xml and pass it to an xslt stylesheet.

May be from your application the execution of the stylesheet on an empty form (Form 1) causes this. Try to handle this by executing the stylesheet only whether the form is not empty.

Furthermore you may want change your stylesheet into this one:

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

    <xsl:output method="text"/>
    <xsl:strip-space elements="*" />

    <xsl:template match="info/a">
        <xsl:value-of select="concat(normalize-space(.), 
            ' ',
            normalize-space(@href))"/>
            <xsl:if test="follwing-sibling::a">
             <xsl:text>&#xA;</xsl:text>
            </xsl:if>
    </xsl:template>

</xsl:stylesheet>

Where normalize-space() is used to ensure that your input data has no unwanted spaces.

Upvotes: 2

jelovirt
jelovirt

Reputation: 5892

You want to use text output method, process only the nodes you want and not output a new line after the last a (or before the first as in the solution below)

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

  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="info">
    <xsl:apply-templates select="a"/>      
  </xsl:template> 

  <xsl:template match="a">
    <xsl:if test="not(position() = 1)" xml:space="preserve">&#xA;</xsl:if>
    <xsl:value-of select="concat(text(), ' ', @href)"/>
  </xsl:template>

You need the xml:spaceon the xsl:text instruction so that it will not be whitespace normalized when the stylesheet is read.

Upvotes: 1

Jollymorphic
Jollymorphic

Reputation: 3530

It may be dependent on what XSL processor you're using, but have you tried the following?

<xsl:output method="text" indent="no" />

Upvotes: 1

Related Questions