public static String toXMLEscapedTextExpandingWhitespace(String text) {
        // Spaces and tabs are handled
        text = text.replaceAll("\t", "         "); // Use eight spaces as tab
        // width.
        int len = text.length();
        StringBuffer result = new StringBuffer(len);
        char myChar;
        for (int i = 0; i < len; ++i) {
            myChar = text.charAt(i);
            switch (myChar) {
                case '&':
                    result.append("&amp;");
                    break;
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case ' ':
                    if (i > 0 && i < len - 1 && (int) text.charAt(i - 1) > 32
                            && (int) text.charAt(i + 1) > 32) {
                        result.append(' ');
                    } else {
                        result.append("&nbsp;");
                    }
                    break;
                default:
                    result.append(myChar);
            }
        }
        return result.toString();
    }