Question

Can I do a conditional formatting on Strings in XSLT?

The input strings are phone numbers in this format:

+1234567890

What I want is; if the 3rd digit (not counting the +) is either 4 or 9 then the string should be shown like

+12 435 67 890 or +12 935 67 890

But if it it any other number:

+12 34 56 78 90

For for all numbers on 3rd digit (except 4 or 8)

      <td>
        <xsl:value-of select="substring($number,1,3)"/>
        <xsl:text>&#xA0;</xsl:text>
        <xsl:value-of select="substring($number,4,2)"/>
        <xsl:text>&#xA0;</xsl:text>
        <xsl:value-of select="substring($number,6,2)"/>
        <xsl:text>&#xA0;</xsl:text>
        <xsl:value-of select="substring($number,8,2)"/>
        <xsl:text>&#xA0;</xsl:text>
        <xsl:value-of select="substring($number,10)"/>
      </td>

If someone has a tip of a more elegant way to format this string, please do tell.

Was it helpful?

Solution

With the following input:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <phone>+1234567890</phone>
    <phone>+1243567890</phone>
    <phone>+1293567890</phone>
</root>

and this stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <xsl:for-each select="root/phone">
            <formatted_phone>
                <xsl:choose>
                    <xsl:when test="substring(., 4, 1) = '4' or substring(., 4, 1) = '9'">
                        <xsl:value-of select="concat(substring(., 1, 3), ' ', substring(., 4, 3), ' ', substring(., 8, 2), ' ', substring(., 9))"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="concat(substring(., 1, 3), ' ', substring(., 4, 2), ' ', substring(., 6, 2), ' ', substring(., 8, 2), ' ', substring(., 10))"/>
                    </xsl:otherwise>
                </xsl:choose>
            </formatted_phone>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

you can have this output

<?xml version="1.0" encoding="utf-8"?>
<formatted_phone>+12 34 56 78 90</formatted_phone>
<formatted_phone>+12 435 78 890</formatted_phone>
<formatted_phone>+12 935 78 890</formatted_phone>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top