【问题标题】:XSLT replace function in FirefoxFirefox 中的 XSLT 替换功能
【发布时间】:2011-05-30 00:26:00
【问题描述】:

我正在尝试通过 XSLT 执行字符串替换,但实际上在 Firefox 中我认为没有办法。

当我通过这样的方式使用 XSLT 2.0 replace() 函数时:

<xsl:value-of select="replace(., 'old', 'new')"/>

我在 Firefox 中收到错误“调用了未知的 XPath 扩展函数”。 当我尝试使用任何与 XSLT 1.0 兼容的模板来执行替换时,我收到错误“XSLT 样式表(可能)包含递归”(当然它包含递归,我看不出没有其他方法可以在 XSLT 中执行字符串替换而没有递归函数)。

因此,没有机会使用 XSLT 2.0 的 replace() 函数,也没有机会使用递归模板。如何使用 XSLT 执行该技巧?请不要建议在服务器端制作它,我实现了我的整个网站以便仅在客户端进行转换,我不能仅仅因为一个问题而回滚,而且在 2011 年我不能使用是不对的像 XSLT 这样强大的技术,因为它的错误和不完整的实现。

编辑:

我使用的代码与此处提供的相同:XSLT Replace function not found

我使用这个 XML 进行测试:

<?xml version="1.0"?>
<?xml-stylesheet href="/example.xsl" type="text/xsl"?>

<content>lol</content>

还有这个 XSLT:

<?xml version="1.0"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>

<xsl:template name="string-replace-all">
<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="string-replace-all">
<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>

<xsl:template match="content">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="lolasd"/>
<xsl:with-param name="replace" select="lol"/>
<xsl:with-param name="by" select="asd"/>
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>

在 Firefox 上,我得到“XSLT 样式表(可能)包含递归”。好吧,当然可以,否则它就不是字符串替换模板。在网上找到的其他使用相同样式的模板也会触发相同的问题。

【问题讨论】:

  • FF 消息很可能意味着无限递归,这意味着存在(真正的)堆栈溢出。您需要更正您的代码。要么提供您的代码(编辑问题并输入代码),要么要求一个有效的 XSLT 1.0 字符串替换解决方案(在 xslt 标记中的各种答案中有很多这样的解决方案)。
  • 您也可以尝试使用 Saxon CE,它是一个 XSLT 2.0 实现,将客户端作为浏览器的一部分运行。
  • 我遗憾地补充说:主要的浏览器项目何时会迁移到更高级的 XSLT 2.0?这整个 Q 将被否定..

标签: xml xslt replace xslt-2.0


【解决方案1】:

有了这份文件

<content>lol</content>

这些参数

<xsl:with-param name="text" select="lolasd"/>
<xsl:with-param name="replace" select="lol"/>
<xsl:with-param name="by" select="asd"/>

将是空的,因此这个条件

<xsl:when test="contains($text,$replace)">

永远是真的,你的代码会无限递归。

我猜你的意图是在 &lt;xsl:with-param&gt; 元素中选择一个字符串而不是一个节点,但你忘记使用引号/撇号。你应该拥有的是类似的东西

<xsl:with-param name="replace" select="'lol'"/>

尽管如此,如果您最终选择了空字符串,您应该添加一个检查参数为空的情况以避免此类问题。

【讨论】:

  • 谢谢,它成功了。我不知道 XSLT 在字符串和节点名称之间产生了这种差异,很高兴知道 :)
猜你喜欢
  • 2010-11-07
  • 2011-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
  • 2019-08-17
  • 2013-05-18
  • 2015-04-14
相关资源
最近更新 更多