code: private static String escapeXml(String source) {
          if (source == null) {
              return null;
          }
          StringBuffer result = new StringBuffer(source.length() * 2);
      
          for (int i = 0; i < source.length(); ++i) {
              char ch = source.charAt(i);
              switch (ch) {
                  case '<':
                      result.append("&lt;");
                      break;
                  case '>':
                      result.append("&gt;");
                      break;
                  case '&':
                      // don't escape already escaped international and special characters
                      int terminatorIndex = source.indexOf(";", i);
                          if (terminatorIndex > 0) {
                              if (source.substring(i + 1, terminatorIndex).matches("#[0-9]+")) {
                                  result.append(ch);
                                  break;
                              }
                          }
                      
                      // note that to other "break" in the above "if" block
                      result.append("&amp;");
                      break;
                  case '"':
                      result.append("&quot;");
                      break;
                  default:
                      result.append(ch);
              }
          }
          return new String(result);
      }
docs: Escapes a String so it may be printed as text content or attribute
  value in a HTML page or an XML file.<p>
  
  This method replaces the following characters in a String:
  <ul>
  <li><b>&lt;</b> with &amp;lt;
  <li><b>&gt;</b> with &amp;gt;
  <li><b>&amp;</b> with &amp;amp;
  <li><b>&quot;</b> with &amp;quot;
  </ul><p>
  
  @param source the string to escape
  @param doubleEscape if <code>false</code>, all entities that already are escaped are left untouched
  
  @return the escaped string