Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xsl:character-map to replace special characters

Tags:

xslt

xslt-2.0

Given an element with a value of:

 <xml_element>Distrib = SU &amp; Prem &amp;lt;&amp;gt; 0</xml_element>

I need to turn &amp;lt; or &amp;gt; into &lt; or &gt; because a downstream app requires it in this format throughout the entire XML document. I would need this for quotes and apostrophes too. I am tryinging a character-map in XSLT 2.0.

<xsl:character-map name="specialchar">
    <xsl:output-character character="&apos;" string="&amp;apos;" />
    <xsl:output-character character="&quot;" string="&amp;quot;" />
    <xsl:output-character character="&gt;" string="&amp;gt;" />
</xsl:character-map>
like image 622
johkar Avatar asked Jul 08 '10 19:07

johkar


1 Answers

The <xsl:character-map> instruction can be used to serialize a single character to any string. However this problem requires more than one character (an ampersand followed by another character to be replaced.

<xsl:character-map> cannot be used to solve such problems.

Here is a solution to this problem, using the XPath 2.0 replace() function:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
   <xsl:value-of select=
    'replace(
        replace(
                replace(., "&amp;lt;", "&lt;"),
                "&amp;gt;",
                "&gt;"
                ),
        "&amp;apos;",
        "&apos;"
        )
    '/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<xml_element>Distrib = SU &amp; &amp;apos;Prem &amp;lt;&amp;gt; 0</xml_element>

the wanted result is produced:

<xml_element>Distrib = SU &amp; 'Prem &lt;&gt; 0</xml_element>
like image 191
Dimitre Novatchev Avatar answered Oct 28 '22 00:10

Dimitre Novatchev