我想使用 XSLT 替换功能来替换文本中的单词
<strong>word</strong>.
Run Code Online (Sandbox Code Playgroud)
我写了以下模板:
<xsl:template name="make-bold">
<xsl:param name="text"/>
<xsl:param name="word"/>
<xsl:variable name="replacement">
<strong><xsl:value-of select="$word"/></strong>
</xsl:variable>
<xsl:value-of select="replace($text, $word, $replacement )" />
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
不幸的是,尽管其余部分有效,但 和没有渲染。
有人可以帮助我吗?
最好的,随都
那么替换函数http://www.w3.org/TR/xpath-functions/#func-replace接受一个字符串并返回一个字符串。您似乎想要创建一个元素节点,而不是一个简单的字符串。在这种情况下,使用analyze-string 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>
Run Code Online (Sandbox Code Playgroud)
当您使用 XSLT 2.0 处理器(例如 Saxon 9)针对以下输入示例运行该程序时
<html>
<body>
<p>This is an example with foo and bar words.</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出如下:
<html>
<body>
<p>This is an example with <strong>foo</strong> and <strong>bar</strong> words.</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8858 次 |
| 最近记录: |