code: private static String filter(String s) {
  		int len = s.length();
  		StringBuilder filtered = new StringBuilder(len);
  		int pos = 0;
  		while(pos < len) {
  			char ch1 = s.charAt(pos++);
  			if(Character.isHighSurrogate(ch1)) {
  				// Handle surrogates
  				if(pos < len) {
  					char ch2 = s.charAt(pos++);
  					if(Character.isLowSurrogate(ch2)) {
  						if(isValidCharacter(Character.toCodePoint(ch1, ch2))) {
  							filtered.append(ch1).append(ch2);
  						}
  					} else {
  						// High surrogate not followed by low surrogate, invalid
  					}
  				} else {
  					// High surrogate at end of string, invalid
  				}
  			} else {
  				// Not surrogates
  				if(isValidCharacter(ch1)) {
  					filtered.append(ch1);
  				}
  			}
  		}
  		assert filtered.length() <= len;
  		return filtered.length() != len ? filtered.toString() : s;
  	}
docs: Filters invalid XML characters.