【问题标题】:I need to update phone number in XLST to remove '+' '-' and phone extension我需要更新 XSLT 中的电话号码以删除“+”“-”和电话分机
【发布时间】:2020-03-29 19:47:03
【问题描述】:

我需要使用 XSLT 将电话号码从 +1 111-111-1234 x 7777777 格式转换为 11111111234。我曾尝试使用 translate('+'-'-') 但这会导致氧气错误。

谢谢

【问题讨论】:

标签: xml xslt numbers translate


【解决方案1】:

我确信有一种更简洁的方法可以使用正则表达式来做到这一点,但这很有效:

 <xsl:variable name="phoneNumber" select="'+1 111-111-1234 x 7777777'"/>
 <xsl:value-of select="replace(replace(substring-after(substring-before($phoneNumber,'x'),'+'),' ',''),'-','')"/>

所以如果你把它分解: 'x' 之前的子字符串, '+' 之后的子字符串, 用''替换'', 将 '-' 替换为 ''。

工作示例:https://xsltfiddle.liberty-development.net/jz1PuPt

【讨论】:

  • 是的,使用正则表达式更简洁:replace(substring-before($phoneNumber,'x'),'\D','')
【解决方案2】:

translate() 的签名是:translate(string, string, string)

根据规范(上面链接),它“返回第一个参数字符串,其中第二个参数字符串中出现的字符被第三个参数字符串中相应位置的字符替换”。

所以如果要从字符串中删除除数字以外的所有字符,首先需要确定这些字符是什么:

translate(.,'0123456789','')

如果. 的字符串值为+1 111-111-1234 x 7777777,则结果为字符串+ -- x

现在我们可以将这些字符从. 中翻译出来:

translate(.,'+ -- x ','')

我们可以做的是嵌套两个 translate() 调用,以便内部调用的输出用作外部调用的第二个参数字符串:

translate(.,translate(.,'0123456789',''),'')

这几乎给了我们想要的输出:

111111112347777777

但我们还有额外的7777777。我们需要在外调用中获取x之前的字符串...

translate(substring-before(.,'x'),translate(.,'0123456789',''),'')

这给了我们想要的输出:

11111111234

注意:我们也可以在内部翻译调用中使用substring-before(这会导致+ --(注意x 缺失)),但这并不会真正改变输出中的任何内容。

这是一个完整的例子...

XML 输入

<test>+1 111-111-1234 x 7777777</test>

XSLT 1.0(有关 XSLT 2.0+ 选项,请参阅其他答案(以及我对该答案的评论))

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="test">
    <xsl:copy>
      <xsl:value-of select="translate(substring-before(.,'x'),
        translate(.,'0123456789',''),'')"/>      
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

输出

<test>11111111234</test>

工作小提琴:http://xsltfiddle.liberty-development.net/bwdwsf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-28
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2020-10-29
    相关资源
    最近更新 更多