Skip to content

Instantly share code, notes, and snippets.

@lucasgautheron
Forked from ScalaWilliam/enrich.xsl
Last active November 16, 2015 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasgautheron/4d2d56397a906cde3320 to your computer and use it in GitHub Desktop.
Save lucasgautheron/4d2d56397a906cde3320 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:lucas="urn:woop:lucas"
exclude-result-prefixes="xs lucas"
version="2.0">
<xsl:variable name="persons" select="//people/person"/>
<xsl:function name="lucas:find-matching-person" as="item()?">
<xsl:param name="text"/>
<xsl:copy-of select="($persons[contains($text, @name)])[1]"/>
</xsl:function>
<xsl:function name="lucas:add-links" as="item()*">
<xsl:param name="text"/>
<xsl:variable name="person" select="lucas:find-matching-person($text)"/>
<xsl:choose>
<xsl:when test="$person">
<xsl:value-of select="substring-before($text, $person/@name)"/>
<a href="{$person/@id}"><xsl:value-of select="$person/@name"/></a>
<xsl:copy-of select="lucas:add-links(substring-after($text, $person/@name))"/>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$text"/></xsl:otherwise>
</xsl:choose>
</xsl:function>
<xsl:template match="text//text()[lucas:find-matching-person(.)]">
<xsl:copy-of select="lucas:add-links(.)"/>
</xsl:template>
<xsl:template match="node()|@*">
<xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<document>
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people>
<text>Hello <strong>John</strong>, say hi to Mary</text>
</document>
<?xml version="1.0" encoding="UTF-8"?><document>
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people>
<text>Hello <strong><a href="john">John</a></strong>, say hi to <a href="mary">Mary</a></text>
</document>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment