tags:

views:

37

answers:

1

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; '&'amp;gt; into '&'lt; '&'gt;

(forgive the tick marks around the ampersands above, I couldn't get it to format right)

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>
+2  A: 

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"&gt;
    <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>
Dimitre Novatchev