Created
July 17, 2012 09:28
-
-
Save dzwillpower/3128328 to your computer and use it in GitHub Desktop.
将一个String中的特殊字符用转义字符代替的方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @return String with special XML characters escaped. | |
*/ | |
public static String escapeXml(String s) { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0, len = s.length(); i < len; ++i) { | |
char c = s.charAt(i); | |
switch (c) { | |
case '<': sb.append("<"); break; | |
case '>': sb.append(">"); break; | |
case '"': sb.append("""); break; | |
case ''': sb.append("'"); break; | |
case '&': sb.append("&"); break; | |
default: sb.append(c); | |
} | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment