Support Wikipedia Follow My Heart: Escape XML Strings in JAVA

2011年10月5日星期三

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.


       /**
               
<->&lt;
>->&gt;
"->&quot;
'->&apos;
&->&amp;

**/


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;
}



没有评论:

发表评论