Support Wikipedia Follow My Heart: Escape XML Strings in JAVA


Escape XML Strings in JAVA

XML is convenient. But some special characters cannot be presented in XML directly.

So we need to "escape" these characters, find valid character to replace them.



private String escape(String src) {
String result = new String(src.trim());
result = result.replaceAll("&", "&amp;");
result = result.replaceAll("<", "&lt;");
result = result.replaceAll(">", "&gt;");
result = result.replaceAll("\"", "&quot;");
result = result.replaceAll("\'", "&apos;");

return result;