简体   繁体   English

在xslt中进行替换的最佳(更快)方法是什么

[英]What is the best(more fast) way to do replace in xslt

What is the best(more fast) way to do replace in xslt? 在xslt中进行替换的最佳(更快)方法是什么?

1/ With Template 1 /带模板

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

2/ With Extension Object 2 /带扩展对象

public class ToolBox
{
        public string replace(string s, string el, string by)
        {return s.Replace(el, by);}
}

<xsl:value-of select="toolbox:replace($foo,$bar, $fobar)" />

Performance questions depend on knowing what product you are using. 性能问题取决于您所使用的产品。 The native code will almost certainly be faster, but on some processors the overhead of calling an extension function is high. 本地代码几乎可以肯定会更快,但是在某些处理器上,调用扩展功能的开销很高。 So measure it. 所以测量一下。

Or switch to XSLT 2.0. 或切换到XSLT 2.0。

To directly answser your question, I expect the string manipulation method to outperform the XML manipulation due to it not having to parse the XML document. 为了直接回答您的问题,我希望字符串操作方法胜过XML操作,因为它不必解析XML文档。

However, you should consider whether you want your replacement to be sensitive to the XML nature of the document or not. 但是,您应该考虑是否要让替换对文档的XML性质敏感。 Ie do you simply want to: 即,您是否只是想:

  1. Alter the text of the document, replacing one string with another, irrespective of whether this occurs in an element name, text node, comment, &c. 更改文档的文本,用一个字符串替换为另一个字符串,而不管该字符串是否出现在元素名称,文本节点,注释和&c中。 A string replacement, if not carefully controlled, could also result in an invalid resultant document, eg a string replacement of <hello> to <there> would alter a starting <hello> element but not the closing, </there> element. 如果不仔细控制字符串替换,也可能导致无效的结果文档,例如,将<hello>替换为<there>的字符串将更改起始的<hello>元素,但不会更改结束的</there>元素。
  2. Alter the XML in an context sensitive manner, allowing precise changes to particular elements, attributes or texts, without destroying the document structure. 以上下文相关的方式更改XML,允许对特定元素,属性或文本进行精确更改,而不会破坏文档结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM