title: Replace xml special characters in Java String
body: <p>We are fetching XML from one source and then passing onto another entity for further processing. However, the fetched XML contains special characters in the attribute value which are not acceptable to the next process. 
  For e.g. </p>
  
  <p>Sample Input :</p>
  
  <pre><code>"&lt;Message text="&lt;html&gt;Welcome User, &lt;br&gt; Happy to have you. &lt;br&gt;.&lt;/html&gt;"
  </code></pre>
  
  <p>Expected Output:</p>
  
  <pre><code>"&lt;Message text="&amp;lt;html&amp;gt;Welcome User, &amp;lt;br&amp;gt; Happy to have you. &amp;lt;br&amp;gt;.&amp;lt;/html&amp;gt;"&gt;
  </code></pre>
  
  <p>Sample Input : <code>&lt;Message text="&lt;html&gt;Welcome User, &lt;br&gt; Happy to have you. &lt;/html&gt;" Multi="false"&gt; &lt;Meta source="system" dest="any"&gt;&lt;/Meta&gt;&lt;/Message&gt;</code></p>
  
  <p>Output: <code>&lt;Message text="&amp;lt;html&amp;gt;Welcome User, &amp;lt;br&amp;gt; Happy to have you. &amp;lt;/html&amp;gt;" Multi="false"&gt; &lt;Meta source="system" dest="any"&gt;&lt;/Meta&gt;&lt;/Message&gt;</code></p>
  
  <p>But the <code>&lt;br&gt;</code> won't be replaced in case the input has multiple <code>&lt;br&gt;</code> tags.</p>
  
  <p>We are using following code :</p>
  
  <pre><code>String xml = "&lt;Message text=\"&lt;html&gt;Welcome User, &lt;br&gt; Happy to have you. &lt;br&gt;.&lt;/html&gt;\" Multi=\"false\"&gt;&lt;Meta source=\"system\" dest=\"any\"&gt;&lt;/Meta&gt;&lt;/Message&gt;";
  System.out.println("ORG:" + xml);
  xml = replaceChars(xml);
  System.out.println("NEW:" + xml);
  
  private static String replaceChars(String xml)
          {
             xml = xml.replace("&amp;", "&amp;amp;");
             xml = xml.replaceAll("\"&lt;([^&lt;]*)&gt;", "\"&amp;lt;$1&amp;gt;");
              xml = xml.replaceAll("&lt;/([^&lt;]*)&gt;\"", "&amp;lt;/$1&amp;gt;\"");
              xml = xml.replaceAll("\"([^&lt;]*)&lt;([^&lt;]*)&gt;([^&lt;]*)\"", "\"$1&amp;lt;$2&amp;gt;$3\"");
  
              return xml;
          }
  </code></pre>