Re: [xsl] stripping leading and trailing blanks of a value?

Subject: Re: [xsl] stripping leading and trailing blanks of a value?
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Tue, 09 Mar 2010 12:11:25 -0500
At 2010-03-09 18:05 +0100, Ben Stover wrote:
Assume I have a XML doc where occasionally values appear with leading and trailing blanks similar to

<aaa>
<bbb>
'3 blanks'somevalue'4 blanks'
</bbb>
</aaa>

Because blanks are probably removed by the mailing list system I put 'n blanks' in the code above.
In reality real blanks are meant.


So how can I strip all such leading and trailing blanks (nad line breaks) with XSLT?

The normalize-space() will remove leading and trailing white-space, and reduce embedded sequences of white-space characters to a single space.


translate(normalize-space($value),' ','')

... will remove those embedded single spaces as well, leaving only non-white-space characters.

In XSLT 2 you could write: replace($value,'\s+','')

The stripping should applied only to "atomic" values. That means that blanks between e.g.
<aaa> and <bbb> should be kept. So the result should look like


<aaa>
<bbb>somevalue</bbb>
</aaa>

Then you only want to apply these to those text nodes that have non-white-space characters.


Moreover how can I strip all "atomic" blanks in a whole XML doc and not only from a particular tag value?

During the building of the source tree you can remove all white-space-only text nodes by using:


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

But be careful ... if you have:

  <aaa>
    <bbb>   </bbb>
  </aaa>

... did you want the spaces of <bbb> preserved?

If so, then something like:

<xsl:strip-space elements="*[*]"/>

... would only strip the white-space-only text nodes from those elements with element children, not those elements without element children. The attribute value is a match pattern.

This stripping happens during the building of the source node tree ... you aren't informed if there were any that were stripped before you see the source node tree.

I hope this helps.

. . . . . . . . . Ken

--
XSLT/XQuery training:      after http://XMLPrague.cz 2010-03-15/19
XSLT/XQuery training:         San Carlos, California 2010-04-26/30
Principles of XSLT for XQuery Writers: San Francisco,CA 2010-05-03
XSLT/XQuery training:                 Ottawa, Canada 2010-05-10/14
XSLT/XQuery/UBL/Code List training: Trondheim,Norway 2010-06-02/11
Vote for your XML training:   http://www.CraneSoftwrights.com/s/i/
Crane Softwrights Ltd.          http://www.CraneSoftwrights.com/s/
G. Ken Holman                 mailto:gkholman@xxxxxxxxxxxxxxxxxxxx
Male Cancer Awareness Nov'07  http://www.CraneSoftwrights.com/s/bc
Legal business disclaimers:  http://www.CraneSoftwrights.com/legal

Current Thread