I need to escape the XML string before transform into an XML file. I do it like this:
Java Code :
public static final String[][] XML_ENTITIES = {
{"&","&"},{">",">"},{"<","<","'","'","\"","""}
};
public static String escape(String str){
for(int i=0;i<XML_ENTITIES.length;i++){
String name = XML_ENTITIES[i][0];
String value = XML_ENTITIES[i][1];
int idx = str.indexOf(name);
if(idx > -1){
str = str.replace(name, value);
}
}
return str;
}
It works fine but it fails in some cases .
Example :
escape(">>,,a,a<<")
Output:
>>,,a,a<<
Failure Case:
escape("&>,,a,a<<")
Output:
&amp;>,,a,a<<
If a xml string contains &
no need to escape the &
character in the string . If I unescape
the string and do escape it works fine . How can I do without unescaping?