xslt用超链接替换文本

时间:2015-08-06 22:12:23

标签: xml xslt xslt-2.0

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

替换所有出现的 Google 字样

听起来很简单,但我在xslt文件中这样做。我通常可以使用函数replace,但它只在用字符串替换字符串时才有效(不允许使用任何元素)。

对此的任何帮助或指示将非常感激。谢谢。

1 个答案:

答案 0 :(得分:3)

此问题与此问题类似: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>
相关问题