title: Replacing and maintaining character entities through multiple transformations
body: <p>Problem: We have character entities come to our systems in various formats (Ex: <code>&amp;amp;</code> and <code>&amp;amp;amp;</code>) and we need to convert them to a standard XML character entities if needed (<code>&amp;amp &amp;lt; &amp;gt; &amp;apos; &amp;quot;</code>) and then maintain them as entities through a couple of separate tranformations. </p>
  
  <p>Given XML of:</p>
  
  <pre><code>&lt;rootelm&gt;
   &lt;testdata&gt;&amp;amp;apos; &amp;amp;gt; &amp;amp;lt; &amp;amp;quot;&lt;/testdata&gt;
  &lt;/rootelm&gt;
  </code></pre>
  
  <p>and a stylesheet of (based on <a href="https://stackoverflow.com/questions/3207297/xslcharacter-map-to-replace-special-characters">xsl:character-map to replace special characters</a>):</p>
  
  <pre><code>&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"&gt;
   &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt;
   &lt;!-- COPY EVERYTHING --&gt;
   &lt;xsl:template match="node() | @*"&gt;
    &lt;xsl:copy&gt;
     &lt;xsl:apply-templates select="@* | node()"&gt;
      &lt;xsl:sort select="local-name()"/&gt;
     &lt;/xsl:apply-templates&gt;
    &lt;/xsl:copy&gt;
   &lt;/xsl:template&gt;
   &lt;xsl:variable name="quote"&gt;
    &lt;xsl:text&gt;&amp;amp;quot;&lt;/xsl:text&gt;
   &lt;/xsl:variable&gt;
   &lt;xsl:variable name="quote2"&gt;
    &lt;xsl:value-of select="string('&amp;quot;')"/&gt;
   &lt;/xsl:variable&gt;
   &lt;xsl:template match="text()[contains(.,'&amp;amp;lt;') or contains(.,'&amp;amp;gt;') or contains(.,'&amp;amp;quot;') or contains(.,'&amp;amp;apos;')]"&gt;
    &lt;xsl:value-of select='replace(
    replace(
     replace(
      replace(., "&amp;amp;lt;", "&amp;lt;"),
     "&amp;amp;gt;",
     "&amp;gt;"
     ),
    "&amp;amp;apos;",
    "&amp;apos;"
    ),
    $quote,
    $quote2
   )
      ' /&gt;
   &lt;/xsl:template&gt;
  &lt;/xsl:stylesheet&gt;
  </code></pre>
  
  <p>How can I keep the apostrophe's and quotes as entities (source system expects/needs it)?</p>
  
  <p>Current Output:</p>
  
  <pre><code>&lt;rootelm&gt; 
     &lt;testdata&gt;' &amp;gt; &amp;lt; "&lt;/testdata&gt;
  &lt;/rootelm&gt;
  </code></pre>