User501
User501

Reputation: 347

Need to remove the space element values using XSL

I have two types of XML elements, one type is

First XML:

<Body>
<h1>aaa</h1>
<h1>bbb</h1>
<h1>ccc</h1>
</Body>

Second XML:

<Body>
<h1> </h1>
<h1>aaa</h1>
<h1>bbb</h1>
</Body>

XSL I'm using as

<xsl:strip-space elements="h1"/>

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

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

   <xsl:template match="h1"/>

Output I'm getting correctly for first XML as like:

<Body>
<h1>aaa bbb ccc</h1>
</Body>

But even I used strip-space element as h1 for the second xml, I'm getting like below:

<Body>
<h1> aaa bbb</h1>
</Body>

Expected output be like

<Body>
<h1>aaa bbb</h1>
</Body>

I Need to remove the space element of h1. But due to that tag, its combining even the space. I used priority and used the seperate h1[normalize-space()] tag also in the template. But its not working. There is having any way to avoid this. Please suggest. I'm using XSLT 2.0 and saxon-PE 9.6.0.7. Thanks in advance

Upvotes: 0

Views: 88

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117100

Need to remove the space element of h1.

The space that you see is not the space in the first h1 element. It is the separator between the empty string in the first h1and the "aaa" string in the second h1 element. You can verify this by doing:

<xsl:template match="Body">
      <xsl:copy>
         <h1><xsl:value-of select="h1" separator="-"/></h1>
      </xsl:copy>
 </xsl:template>

Demo: http://xsltransform.net/pNmBy1v

To remove the extra space, you could exclude the empty h1 elements (as suggested by Martin Honnen while I was writing this), or apply normalize-space() to the result.

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167716

I think using <h1><xsl:value-of select="h1[normalize-space()]"/></h1> instead of <h1><xsl:value-of select="h1"/></h1> should be an easy fix.

Upvotes: 1

Related Questions