【问题标题】:xslt replace text with hyperlinkxslt 用超链接替换文本
【发布时间】:2015-08-06 22:12:23
【问题描述】:

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

替换所有出现的词 Google

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

对此的任何帮助或指示将不胜感激。谢谢。

【问题讨论】:

  • 什么版本的 XSLT?

标签: xml xslt xslt-2.0


【解决方案1】:

本题与本题类似: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>

【讨论】:

  • 这对我来说根本不起作用,但我会将此标记为答案 - 因为它是彻底的,它将引导我走向正确的道路。做一个简单的替换需要这么多工作,这很可悲。再次感谢。
  • “Google”一词仍在文档中(不是超链接),但应该可以使用。现在由我来完成这项工作。
  • @HerbMeehan - 这是一个工作示例。希望对您有所帮助:xsltransform.net/eiZQaGe
  • 谢谢。我真心的。希望我能给你另一个赞成票。谢谢。
  • @HerbMeehan - 完全没问题。很高兴我能帮上忙!
猜你喜欢
  • 2018-03-22
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 2013-09-13
  • 2022-12-05
  • 2012-02-18
相关资源
最近更新 更多