Reputation: 177
I need to replace all occurrences of the word Google with the hyperlink <a href="http://google.com">Google</a>
Sounds easy enough, but I'm doing this within an xslt file. I could normally use the function replace, but it only works when replacing a string with a string (no elements are allowed).
Any help or pointers on this would be much appreciated. Thanks.
Upvotes: 1
Views: 1032
Reputation: 52858
This question is similar to this question: Replacing strings in various XML files
You would just need to change what you're replacing.
Here's an example that shows a possible modification.
XML Input
<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 Output
<doc>
<test>This should be a link to google: <a href="http://www.google.com">Google</a>
</test>
</doc>
Upvotes: 3