Replacing XML value in XSLT

前端 未结 3 1403
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 17:26

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


Th

相关标签:
3条回答
  • 2021-01-16 18:03

    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>
    
    0 讨论(0)
  • 2021-01-16 18:16

    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

    0 讨论(0)
  • 2021-01-16 18:24

    another xslt 1.0 template from exslt.org

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

    0 讨论(0)
提交回复
热议问题