2

How can I replace a string with an XML element using XSLT 1.0?

Source:

<body>This has a keyword and may have another keyword</body>

Desired output:

<body>This has a <kw>keyword</kw> and may have another <kw>keyword</kw></body>

I have the following template but it only supports replacing the string with text.

<xsl:template name="replace-string">
    <xsl:param name="text"/>
    <xsl:param name="replace"/>
    <xsl:param name="with"/>
    <xsl:choose>
        <xsl:when test="contains($text,$replace)">
            <xsl:value-of select="substring-before($text,$replace)"/>
            <xsl:value-of select="$with"/>
            <xsl:call-template name="replace-string">
                <xsl:with-param name="text" select="substring-after($text,$replace)"/>
                <xsl:with-param name="replace" select="$replace"/>
                <xsl:with-param name="with" select="$with"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Any tips would be helpful.

Thanks.

1 Answer 1

1

From what you already have, it looks like all that is missing is <xsl:element name="keyword"/> And if the element name is dynamic, use <xsl:element name="{XP}"/> where XP is an XPath expression.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I do multiple replacements in the same text? If I store the results in a variable they seem to get lost.
The question is a bit vague. Please provide your XML and XSLT together with the desired output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.