code: private String escapeText(StringBuilder sb, String text)
     {
        int length = text.length();
        char c;
  
        sb.setLength(0);
  
        for (int loop = 0; loop < length; loop++)
        {
           c = text.charAt(loop);
  
           switch (c)
           {
              case '<':
              {
                 sb.append("&lt;");
                 break;
              }
  
              case '>':
              {
                 sb.append("&gt;");
                 break;
              }
  
              case '&':
              {
                 sb.append("&amp;");
                 break;
              }
  
              default:
              {
                 if (validXMLCharacter(c))
                 {
                    if (c > 127)
                    {
                       sb.append("&#" + (int) c + ";");
                    }
                    else
                    {
                       sb.append(c);
                    }
                 }
  
                 break;
              }
           }
        }
  
        return (sb.toString());
     }
docs: Quick and dirty XML text escape.
  
  @param sb working string buffer
  @param text input text
  @return escaped text