title: Java RegEx: Replace all xml characters with their entity number
body: <p>I am trying to port a function I wrote in ActionScript to Java and I am having a bit of trouble. I have included the function below. I found <a href="https://stackoverflow.com/a/2563382/1762224">this response to question #375420</a>, but do I really need to write a separate class? Thanks.</p>
  
  <pre class="lang-javascript prettyprint-override"><code>public static function replaceXML(str:String):String {
    return str.replace(/[\"'&amp;&lt;&gt;]/g, function($0:String):String {
      return StringUtil.substitute('&amp;#{0};', $0.charCodeAt(0));
    });
  }
  </code></pre>
  
  <p><strong>Input</strong></p>
  
  <pre><code>&lt;root&gt;&lt;child id="foo"&gt;Bar&lt;/child&gt;&lt;/root&gt;
  </code></pre>
  
  <p><strong>Output</strong></p>
  
  <pre><code>&amp;#60;root&amp;#62;&amp;#60;child id=&amp;#34;foo&amp;#34;&amp;#62;Bar&amp;#60;/child&amp;#62;&amp;#60;/root&amp;#62;
  </code></pre>
  
  <hr>
  
  <p><strong><em>UPDATE</em></strong></p>
  
  <p>Here is my solution if anyone is wondering. Thanks <a href="https://stackoverflow.com/users/1026805">Sri Harsha Chilakapati</a>.</p>
  
  <pre class="lang-java prettyprint-override"><code>public static String replaceXML(final String inputStr) {
    String outputStr = inputStr;
    Matcher m = Pattern.compile("[&amp;&lt;&gt;'\"]").matcher(outputStr);
    String found = "";
    while (m.find()) {
      found = m.group();
      outputStr = outputStr.replaceAll(found,
        String.format("&amp;#%d;", (int)found.charAt(0)));
    }
    return outputStr;
  }
  </code></pre>