protected String escapeElementEntities(String text) {
        char[] block = null;
        int i, last = 0, size = text.length();
        for ( i = 0; i < size; i++ ) {
            String entity = null;
            char c = text.charAt(i);
            switch( c ) {
                case '<' :
                    entity = "&lt;";
                    break;
                case '>' :
                    entity = "&gt;";
                    break;
                case '&' :
                    entity = "&amp;";
                    break;
                case '\t': case '\n': case '\r':
                    // don't encode standard whitespace characters
                    if (preserve) {
                      entity=String.valueOf(c);
                    }
                    break;
                default:
                    if (c < 32 || shouldEncodeChar(c)) {
                        entity = "&#" + (int) c + ";";
                    }
                    break;
            }
            if (entity != null) {
                if ( block == null ) {
                    block = text.toCharArray();
                }
                buffer.append(block, last, i - last);
                buffer.append(entity);
                last = i + 1;
            }
        }
        if ( last == 0 ) {
            return text;
        }
        if ( last < size ) {
            if ( block == null ) {
                block = text.toCharArray();
            }
            buffer.append(block, last, i - last);
        }
        String answer = buffer.toString();
        buffer.setLength(0);
        return answer;
    }
This will take the pre-defined entities in XML 1.0 and
convert their character representation to the appropriate
entity reference, suitable for XML attributes.
@param text the entities to escale
@return the escaped entities
xmppserver/src/main/java/org/jivesoftware/util/XMLWriter.java