好替换功能http://www.w3.org/TR/xpath-functions/#func-replace接受一个字符串并返回一个字符串。你似乎想创建一个元素节点,而不是一个简单的字符串。在这种情况下,使用分析字符串http://www.w3.org/TR/xslt20/#analyze-string而不是替换可能会有所帮助。
下面是一个示例XSLT 2.0样式表:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output method="html" indent="no"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*, node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="text()" mode="wrap">
<xsl:with-param name="words" as="xs:string+" select="('foo', 'bar')"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="text()" mode="wrap">
<xsl:param name="words" as="xs:string+"/>
<xsl:param name="wrapper-name" as="xs:string" select="'strong'"/>
<xsl:analyze-string select="." regex="{string-join($words, '|')}">
<xsl:matching-substring>
<xsl:element name="{$wrapper-name}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>
当运行用XSLT 2.0处理器等撒克逊9对以下输入采样
<html>
<body>
<p>This is an example with foo and bar words.</p>
</body>
</html>
输出如下:
<html>
<body>
<p>This is an example with <strong>foo</strong> and <strong>bar</strong> words.</p>
</body>
</html>
+1 Right XSLT 2.0 answer。但我认为'p'匹配规则是没有必要的。如果你想只将包装规则应用到'p'的文本节点子节点(甚至更好,子节点),你可以使用这个模式'p/text()'(或'p // text()') – 2010-12-10 13:17:23
你,马丁和亚历杭德罗。建议的解决方案运作良好! Suidu – Suidu 2010-12-11 06:34:52