Unnamed user
Unnamed user

Reputation: 181

XSLT to remove spaces from text nodes

I want to trim extra spaces from text values of my XML. I tried various options available over internet but none of them worked for me. I cannot use normalize-space() because I have to remove only leading & trailing spaces.

XML:

<BillEvent>
<TransactionInfo>
    <EventDate>   2016-04-13T05:40:28  </EventDate>
   </TransactionInfo>  
         <CaseID>    Since     this   is a CDATA section! </CaseID>
        <BillGroup>
                <Bill>   
                <BillNumber>     253545666847</BillNumber>
                <ToDate> 2016-05-31     </ToDate>
                <BillActivityCode tc="1"/>
                <BillCreationDate>     Since this is a CDATA section!   </BillCreationDate>
            </Bill>
        </BillGroup>       
</BillEvent>

Expected output:

<BillEvent>
<TransactionInfo>
    <EventDate>2016-04-13T05:40:28</EventDate>
   </TransactionInfo>  
         <CaseID>Since     this   is a CDATA section!</CaseID>
        <BillGroup>
                <Bill>   
                <BillNumber>253545666847</BillNumber>
                <ToDate>2016-05-31</ToDate>
                <BillActivityCode tc="1"/>
                <BillCreationDate>Since this is a CDATA section!</BillCreationDate>
            </Bill>
        </BillGroup>       
</BillEvent>        

i.e. only leading & trailing spaces should be removed.

XSLT used:

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

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

<xsl:template match="text()">
<xsl:copy>
<xsl:sequence-of select="replace(., '^\s+|\s+$', '')"/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

I also tried translate(.,' &#x9;&#xa;&#xd;', '') & replace(.,'^ +',''). I am not sure what is wrong with my code because of which none of them worked. I would appreciate any help on this.

Upvotes: 1

Views: 1417

Answers (1)

Tim C
Tim C

Reputation: 70648

Your regular expression in replace is correct. The problem is that you you have an xsl:copy in your template, which copies the text as-is, and it then doesn't make sense to try to add something as a child of a text node.

Additionally, xsl:sequence-of is not a valid command (although that maybe a typo in your question).

Try this template...

<xsl:template match="text()">
  <xsl:value-of select="replace(., '^\s+|\s+$', '')"/>
</xsl:template>

Upvotes: 1

Related Questions