code: private static String xmlEncode(String input, boolean attribute) {
      if (input == null || input.length() == 0) {
        return attribute ? "\"\"" : input;
      }
      StringBuilder output = new StringBuilder();
      if (attribute) {
        output.append(0); // reserve space for leading quote
      }
      char quoteChar = 0;
      for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        switch (ch) {
          case '<':
            output.append("&lt;");
            break;
          case '>':
            output.append("&gt;");
            break;
          case '&':
            output.append("&amp;");
            break;
          case '"':
            if (attribute && quoteChar == '"') {
              output.append("&quot;");
            }
            else {
              output.append(ch);
              quoteChar = '\'';
            }
            break;
          case '\'':
            if (attribute && quoteChar == '\'') {
              output.append("&apos;");
            }
            else {
              output.append(ch);
              quoteChar = '"';
            }
            break;
          case 0x0009: // tab
          case 0x000A: // linefeed
          case 0x000D: // carriage return
            if (attribute) {
              output.append("&#");
              output.append((int) ch);
              output.append(";");
            }
            else {
              output.append(ch);
            }
            break;
          default:
            if (ch < 32 || ch >= 0xFFFE) {
              throw new IllegalArgumentException("UTF-16 Codepoint 0x" + Integer.toString(ch, 16) + " is not valid for XML content");
            }
            output.append(ch);
        }
      }
      if (attribute) {
        if (quoteChar == 0) {
          quoteChar = '"';
        }
        output.setCharAt(0, quoteChar);
        output.append(quoteChar);
      }
      return output.toString();
    }
docs: Properly encodes user input for inclusion in an XML document.
  @param input the input to encode
  @param attribute is this for an attribute? (returned value will be pre-quoted)
  @return the XML-encoded input