Java examples for XML:XML String Escape
Escapes an XML string by replacing the characters shown below with their equivalent entity references as defined by the XML specification
import java.io.PrintWriter; import java.io.StringWriter; public class Main{ public static void main(String[] argv){ String str = "<java2s.com>"; System.out.println(encodeXML(str)); }//from w w w. j av a2s. c o m /** * Escapes an XML string by replacing the characters shown below with their * equivalent entity references as defined by the XML specification.<p> * * <table> * <tr><td>Character</td><td>Entity Reference</td></tr> * <tr><td><</td><td>&lt;</td></tr> * <tr><td>></td><td>&gt;</td></tr> * <tr><td>&</td><td>&amp;</td></tr> * <tr><td>'</td><td>&apos;</td></tr> * <tr><td>"</td><td>&quot;</td></tr> * </table> * * @param str The source string * @return The escaped string */ public static String encodeXML(String str) { if (str == null) return null; StringBuilder b = new StringBuilder(); int cnt = str.length(); for (int i = 0; i < cnt; i++) { char c = str.charAt(i); switch (c) { case '<': b.append("<"); break; case '>': b.append(">"); break; case '\'': b.append("'"); break; case '"': b.append("""); break; case '&': b.append("&"); break; default: b.append((char) c); } } return b.toString(); } }