xslt 用超链接替换文本

xslt replace text with hyperlink

我需要用超链接 <a href="http://google.com">Google</a>

替换所有出现的单词 Google

听起来很简单,但我是在 xslt 文件中执行此操作。我通常可以使用函数替换,但它只在用字符串替换字符串时有效(不允许元素)。

如有任何帮助或指点,我们将不胜感激。谢谢。

这个问题类似于这个问题:Replacing strings in various XML files

您只需要更改要替换的内容即可。

这是一个显示可能修改的示例。

XML 输入

<doc>
    <test>This should be a link to google: Google</test>
</doc>

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:param name="list">
        <words>
            <word>
                <search>Google</search>
                <replace>http://www.google.com</replace>
            </word>
            <word>
                <search>Foo</search>
                <replace>http://www.foo.com</replace>
            </word>
        </words>
    </xsl:param>

    <xsl:template match="@*|*|comment()|processing-instruction()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:variable name="search" select="concat('(',string-join($list/words/word/search,'|'),')')"/>
        <xsl:analyze-string select="." regex="{$search}">
            <xsl:matching-substring>
                <a href="{$list/words/word[search=current()]/replace}"><xsl:value-of select="."/></a>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>

XML输出

<doc>
   <test>This should be a link to google: <a href="http://www.google.com">Google</a>
   </test>
</doc>