Java examples for XML:XML String Escape
Unescapes an XML string by replacing the entity references shown below with their equivalent characters as defined by the XML specification
public class Main { public static void main(String[] argv) { String str = "&<java2s.com"; System.out.println(unencodeXML(str)); }//from w w w . j a v a 2s . c o m /** * Unescapes an XML string by replacing the entity references shown below with * their equivalent characters 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 unencodeXML(String str) { if (str == null) return null; StringBuilder b = new StringBuilder(); int c = 0; while (c < str.length()) { if (str.charAt(c) == '&') { String entity = _entity(str, c); if (entity == null) b.append('&'); else { if (entity.equals("lt")) b.append('<'); else if (entity.equals("gt")) b.append('>'); else if (entity.equals("amp")) b.append('&'); else if (entity.equals("apos")) b.append("'"); else if (entity.equals("quot")) b.append('"'); else { b.append("&"); b.append(entity); b.append(";"); } c += entity.length() + 1; } } else b.append(str.charAt(c)); c++; } return b.toString(); } private static String _entity(String src, int ch) { int c = ch + 1; while (c < src.length()) { if (src.charAt(c) == '&') return null; if (src.charAt(c) == ';') return src.substring(ch + 1, c); c++; } return null; } }