xmlxslt-1.0paddingfixed-widthmsxml6

pad string values in xslt 1.0 with leading spaces even when element is empty


I have 2 elements like this:

<PhoneNumber>0870 6071352</PhoneNumber>
<FaxNumber>01722 422301</FaxNumber>

In the output (fixed width text) both of these need to padded with leading spaces to a length of 71 characters

So I tried:

<xsl:value-of select="substring(concat('                                                                       ', msg:ContactDetails/msg:PhoneNumber), string-length(msg:ContactDetails/msg:PhoneNumber) + 1, 71)"/>
<xsl:value-of select="substring(concat('                                                                       ', msg:ContactDetails/msg:FaxNumber), string-length(msg:ContactDetails/msg:FaxNumber) + 1, 71)"/>

but when the element is empty the string-length function above returns 0, so I only got what looks like 59 spaces in my output instead of 71.

I also tried:

<xsl:value-of select="substring(concat('                                                                       ', msg:ContactDetails/msg:PhoneNumber), 12, 71)"/>
<xsl:value-of select="substring(concat('                                                                       ', msg:ContactDetails/msg:FaxNumber),  12, 71)"/>

but the same thing happens when the FaxNumber or Phonenumber elements are empty

How can I change my xsl to handle situations like this?


Solution

  • [answering this old post as I stumbled on it in a search and there was no clear answer]

    in the first example, this will work ONLY if your element is empty. when the length is >0 you are pulling less characters. If the length of the field is 12 you only pull from 12 thru 71, or 59 chars

    In the second you are appending 71 spaces but your substring in only pulling from char 12 thru 71. 71-12 = 59. So again you only get 59 chars.

    This is probably what you want:

    <xsl:value-of select="substring(concat('                                                                       ', msg:ContactDetails/msg:PhoneNumber), string-length(msg:ContactDetails/msg:PhoneNumber) + 1)"/>
    

    The difference being leaving off the last argument on substring so you pull to the last char, not just to char 71.