I am attempting to write a little class to escape characters in an XML document. I am using xpath to get the nodes of the XML document, and passing each node to my class. However, it is not working. I want to change:
"I would like a burger & fries."
to
"I would like a burger & fries."
Here is the code for my class:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MyReplace{
private static final HashMap<String,String> xmlCharactersToBeEscaped;
private Iterator iterator;
private String newNode;
private String mapKey;
private String mapValue;
static {
xmlCharactersToBeEscaped = new HashMap<String,String>();
xmlCharactersToBeEscaped.put("\"",""");
xmlCharactersToBeEscaped.put("'","'");
xmlCharactersToBeEscaped.put("<","<");
xmlCharactersToBeEscaped.put(">",">");
xmlCharactersToBeEscaped.put("&","&");
}
public String replaceSpecialChar(String node){
if(node != null){
newNode = node;
iterator = xmlCharactersToBeEscaped.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry mapEntry = (Map.Entry) iterator.next();
mapKey = mapEntry.getKey().toString();
mapValue = mapEntry.getValue().toString();
if(newNode.contains(mapKey)){
newNode = newNode.replace(mapKey,mapValue);
}
}
return newNode;
} else {
return node;
}
}
}
What is happening is that it is replacing the first special character in the map, the quote, and skipping everything else.