Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip away carriage returns with XSLT only?

Tags:

xml

xslt

xpath

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 ?

like image 905
Stephan Avatar asked Oct 11 '22 15:10

Stephan


1 Answers

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.

like image 172
Emiliano Poggi Avatar answered Oct 14 '22 03:10

Emiliano Poggi