Java: escape XML entities 

There are 4 notes for this topic, click above title to see all notes.
Joined:
04/09/2007
Posts:
784

October 14, 2008 22:43:43    Last update: January 03, 2015 17:14:44
With StringCharacterIterator and StringBuilder:
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class TestEscape {
    public static String escapeXML(String s) {
        StringBuilder result = new StringBuilder();
        StringCharacterIterator i = new StringCharacterIterator(s);
        char c =  i.current();
        while (c != CharacterIterator.DONE ){
            switch (c) {
                case '<':
                    result.append("&lt;");
                    break;

                case '>':
                    result.append("&gt;");
                    break;

                case '"':
                    result.append("&quot;");
                    break;

                case '\'':
                    result.append("&apos;");
                    break;

                case '&':
                    result.append("&amp;");
                    break;

                default:
                    result.append(c);
            }
            c = i.next();
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(escapeXML("a < b"));
    }
}
Share |
| Comment  | Tags