XSLT 2.0:如何仅移除XML中~符号后的空格而非所有空格
问题:仅移除XML中~符号后的空格,保留内容内空格
输入XML
<?xml version="1.0" encoding="utf-8" ?> <section> <Notes>~ CB:C86100011~ NAME:THINKPAD LAPTOP 10~ PART_DESCRIPTION:FD85 FLOOR DRY 25-LB POLY BAG WITH HANDLE~ POL:1~ Price:6.163965~ UnitsofMeasure:EA~ VN:FD85~</Notes> </section>
原方案的问题
原代码使用translate(section/Notes,'~ ','~'),这个函数是字符级替换:它会把字符串中所有的~和空格都替换成~,导致内容里的正常空格也被删除,不符合需求。
正确实现方式
方案1:XSLT 2.0及以上版本(推荐)
使用replace()函数精准匹配~ (波浪号加空格)的组合,替换为~,只会处理波浪号后的空格:
<xsl:template match="/"> <Notes> <xsl:value-of select="replace(section/Notes, '~ ', '~')"/> </Notes> </xsl:template>
方案2:XSLT 1.0版本(兼容旧环境)
XSLT 1.0没有原生replace,可以用递归模板处理字符串,逐个匹配替换~ :
<xsl:template match="/"> <Notes> <xsl:call-template name="trim-tilde-space"> <xsl:with-param name="text" select="section/Notes"/> </xsl:call-template> </Notes> </xsl:template> <xsl:template name="trim-tilde-space"> <xsl:param name="text"/> <xsl:choose> <xsl:when test="contains($text, '~ ')"> <xsl:value-of select="substring-before($text, '~ ')"/> <xsl:text>~</xsl:text> <xsl:call-template name="trim-tilde-space"> <xsl:with-param name="text" select="substring-after($text, '~ ')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template>
最终输出
<Notes>~CB:C86100011~NAME:THINKPAD LAPTOP 10~PART_DESCRIPTION:FD85 FLOOR DRY 25-LB POLY BAG WITH HANDLE~POL:1~Price:6.163965~UnitsofMeasure:EA~VN:FD85~</Notes>
内容的提问来源于stack exchange,提问作者HKmar
相关产品推荐
相关产品推荐

