开发者

xslt 1.0 string replace function

开发者 https://www.devze.com 2023-04-07 11:09 出处:网络
开发者_Python百科I have a string \"aa::bb::aa\" and need to turn it in to \"aa, bb, aa\" I have tried

开发者_Python百科I have a string "aa::bb::aa"

and need to turn it in to "aa, bb, aa"

I have tried

translate(string,':',', ')

but this returns "aa,,bb,,aa"

How can this be done.


A very simple solution (that will work as long as your string value doesn't have spaces):

translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',')
  1. translate ":' into " "
  2. normalize-space() to collapse multiple whitespace characters into a single space " "
  3. translate single spaces " " into ","

A more robust solution would be to use a recursive template:

<xsl:template name="replace-string">
    <xsl:param name="text"/>
    <xsl:param name="replace"/>
    <xsl:param name="with"/>
    <xsl:choose>
      <xsl:when test="contains($text,$replace)">
        <xsl:value-of select="substring-before($text,$replace)"/>
        <xsl:value-of select="$with"/>
        <xsl:call-template name="replace-string">
          <xsl:with-param name="text"
select="substring-after($text,$replace)"/>
          <xsl:with-param name="replace" select="$replace"/>
          <xsl:with-param name="with" select="$with"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

You can use it like this:

<xsl:call-template name="replace-string">
  <xsl:with-param name="text" select="'aa::bb::cc'"/>
  <xsl:with-param name="replace" select="'::'" />
  <xsl:with-param name="with" select="','"/>
</xsl:call-template>


You can use this

Syntax:- fn:tokenize(string,pattern)

Example: tokenize("XPath is fun", "\s+")
Result: ("XPath", "is", "fun")

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号