如何在XSL中去除SSN字段前的星号?
去除SSN字段中的星号(XSLT实现方案)
要彻底清除SSN里的所有星号(不管是开头、中间还是其他位置),直接用XSLT的字符串处理函数就能搞定,以下两种方法都能兼容纯数字、带星号、空值的SSN字段:
方法一:用replace()函数(XSLT 2.0及以上适用,你的XSLT3.0完全支持)
replace()可以通过正则匹配替换所有目标字符,星号是正则元字符,所以要加反斜杠转义。把你原来XSL里输出SSN的代码替换成下面的写法:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"> <xsl:output method="text"/> <xsl:template match="/"> <table> <title> </title> <body> <tr> <th> SSN </th> </tr> <td> <xsl:for-each select="/information/secondBranch"> <tr> <!-- 替换所有星号为空 --> <xsl:value-of select="replace(SSN, '\*', '')"/> </tr> </xsl:for-each> </td> </body> </table> </xsl:template> </xsl:stylesheet>
方法二:用translate()函数(兼容所有XSLT版本)
如果需要兼容更老的XSLT版本,translate()是更稳妥的选择,它能精准替换指定字符:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"> <xsl:output method="text"/> <xsl:template match="/"> <table> <title> </title> <body> <tr> <th> SSN </th> </tr> <td> <xsl:for-each select="/information/secondBranch"> <tr> <!-- 把星号替换为空字符串 --> <xsl:value-of select="translate(SSN, '*', '')"/> </tr> </xsl:for-each> </td> </body> </table> </xsl:template> </xsl:stylesheet>
测试示例(补充带星号的SSN场景)
你可以用下面的XML测试效果,不管星号在什么位置,都会被彻底清除:
<?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl" href="XSLAsterisk.xsl"?> <information> <secondBranch> <SSN>771717771</SSN> </secondBranch> <secondBranch> <SSN>*9991</SSN> </secondBranch> <secondBranch> <SSN>12*34*56</SSN> </secondBranch> <secondBranch> <SSN></SSN> </secondBranch> </information>
内容的提问来源于stack exchange,提问作者bugs account
相关产品推荐
相关产品推荐

