Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created November 13, 2015 21:37
Show Gist options
  • Save fancellu/5e44427e8d34b7051168 to your computer and use it in GitHub Desktop.
Save fancellu/5e44427e8d34b7051168 to your computer and use it in GitHub Desktop.
Example of recursive text replace based on lookup data
<?xml version="1.0" encoding="UTF-8"?>
<document>
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people>
<text>Hello John, say hi to Mary</text>
</document>
<?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:local="local"
exclude-result-prefixes="xs"
version="3.0">
<xsl:variable name="root" select="/document"/>
<xsl:function name="local:replace2" as="xs:string*">
<xsl:param name="text" as="xs:string"/>
<xsl:param name="persons" as="item()*"/>
<xsl:variable name="person" select="head($persons/@name)"/>
<xsl:variable name="replaced" select="replace($text,$person,upper-case($person))"/>
<xsl:choose>
<xsl:when test="empty($persons)"><xsl:value-of select="$text"/></xsl:when>
<xsl:otherwise><xsl:value-of select="local:replace2($replaced,tail($persons))"/></xsl:otherwise>
</xsl:choose>
</xsl:function>
<xsl:template match="/ | @* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="text"><xsl:copy-of select="local:replace2(.,$root/people/person)"></xsl:copy-of></xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?><document>
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people>
Hello JOHN, say hi to MARY
</document>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment