使用xslt 1.0从字符串中删除所有单个字符

时间:2012-02-01 05:03:24

标签: xslt-1.0

<title>
 <article_title>Land a b   c   d      Band</article_title>
</title>

使用以下功能

replace(article_title, '(^[^ ]+)(.+\s+)([^ ]+)$', '$1 $3')

这个字符串被转换为Land Band,这正是我想要的。

但问题是我在xslt 1.0中需要这个解决方案,因为我正在使用的java应用程序只能处理xslt 1.0解析。

1 个答案:

答案 0 :(得分:1)

这个XSLT 1.0转换(有一个讨厌的SO错误,代码没有缩进 - 我为这个视觉混乱道歉......):

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

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()" name="removeSingles">
   <xsl:param name="pText" select="."/>

   <xsl:variable name="vText" select="normalize-space($pText)"/>

   <xsl:if test="string-length($vText)">
    <xsl:variable name="vLeftChars" select=
    "substring-before(concat($vText, ' '), ' ')"/>

    <xsl:if test="string-length($vLeftChars) >1">
     <xsl:value-of select="$vLeftChars"/>
     <xsl:if test=
      "not(string-length($vLeftChars)
          >=
           string-length($vText)
           )
      ">
       <xsl:text> </xsl:text>
      </xsl:if>
    </xsl:if>

    <xsl:call-template name="removeSingles">
     <xsl:with-param name="pText" select=
     "substring-after($vText, ' ')"/>
    </xsl:call-template>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<title>
 <article_title>Land a b   c   d      Band</article_title>
</title>

生成想要的正确结果

<title>
   <article_title>Land Band</article_title>
</title>