code: public static String escapeEntities(String str, boolean strict) {
          StringBuilder buffer;
          char ch;
          String msg;
          String entity;
  
          buffer = null;
          for (int i = 0; i < str.length(); i++) {
              ch = str.charAt(i);
              switch (ch) {
                  case '\t':
                  case '\n':
                  case '\r':
                      entity = null;
                      break;
                  case '<' :
                      entity = "&lt;";
                      break;
                  case '>' :
                      entity = "&gt;";
                      break;
                  case '\'' :
                      entity = "&apos;";
                      break;
                  case '\"' :
                      entity = "&quot;";
                      break;
                  case '&' :
                      entity = "&amp;";
                      break;
                  default :
                      if (ch < 32) {
                          msg = "illegal character code " + (int) ch;
                          if (strict) {
                              throw new IllegalArgumentException(msg);
                          }
                          entity = "[" + msg + "]";
                      } else if (ch < 256) {
                          entity = null;
                      } else {
                          entity = "&#" + (int) ch + ";";
                      }
                      break;
              }
              if (buffer == null) {
                  if (entity != null) {
                      buffer = new StringBuilder(str.length() + 5);
                      buffer.append(str.substring(0, i));
                      buffer.append(entity);
                  }
              } else {
                  if (entity == null) {
                      buffer.append(ch);
                  } else {
                      buffer.append(entity);
                  }
              }
          }
          return buffer == null ? str : buffer.toString();
      }
docs: Same method used for attributes and elements ...
  See http://www.w3.org/TR/REC-xml/#charsets