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