【问题标题】:Using XSLT to Transform Strings使用 XSLT 转换字符串
【发布时间】:2014-05-05 01:54:48
【问题描述】:

我可以在 XSLT 中对字符串进行条件格式化吗?

输入字符串是这种格式的电话号码:

+1234567890

我想要的是;如果 第 3 位(不包括 +)是 4 或 9,则字符串应显示为

+12 435 67 890 或 +12 935 67 890

但如果是其他数字:

+12 34 56 78 90

适用于所有第 3 位数字(4 或 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>

如果有人知道格式化此字符串的更优雅的方式,请告诉。

【问题讨论】:

  • 我建议你使用&lt;xsl:choose&gt;。有一种“聪明”的方法可以在一次计算中提供两种格式 - 但恕我直言,最好有清晰易读的代码。至于“格式化此字符串的更优雅的方式”,您可以使用 concat() 函数 - 但它几乎没有什么区别。 XSLT 本质上是冗长的,没有必要担心它。

标签: string xslt formatting phone-number


【解决方案1】:

使用以下输入:

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

还有这个样式表:

<?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>

你可以有这个输出

<?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>

【讨论】:

    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2021-10-10
    • 2014-01-03
    相关资源
    最近更新 更多