Replacing XML value in XSLT

2019-02-20 23:54发布

问题:

I can't edit XML, I just want to change XML data in an XSLT file.

<xsl:value-of select="Name" disable-output-escaping="yes"/>

The value of XML data is "Northfield Bancorp Inc.(MHC)" and I want to replace it with "Northfield Bancorp Inc." (remove "MHC").

Is there any function available in XSLT which can search and replace the this?

回答1:

If it is just the "(MHC)" at the end of the string you want to remove, this would do:

<xsl:value-of select="
  substring-before(
    concat(Name, '(MHC)'), 
    '(MHC)'
  )
" />

If you want to replace dynamically, you could write a function like this:

<xsl:template name="string-replace">
  <xsl:param name="subject"     select="''" />
  <xsl:param name="search"      select="''" />
  <xsl:param name="replacement" select="''" />
  <xsl:param name="global"      select="false()" />

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

Which would be callable as:

<xsl:call-template name="string-replace">
  <xsl:with-param name="subject"     select="Name" />
  <xsl:with-param name="search"      select="'(MHC)'" />
  <xsl:with-param name="replacement" select="''" />
  <xsl:with-param name="global"      select="true()" />
</xsl:call-template>


回答2:

XSLT 2.0 has a replace() function.

If you're stuck with 1.0, there is a template in the standard library that can stand in for the lack of a native function:

http://prdownloads.sourceforge.net/xsltsl/xsltsl-1.2.1.zip http://xsltsl.sourceforge.net/string.html#template.str:subst



回答3:

another xslt 1.0 template from exslt.org

http://www.exslt.org/str/functions/replace/str.replace.template.xsl



标签: xslt