Current Status

Actively playing with all possible backend services

06 October, 2011

Escaping special characters in Java replace & > < \


i'm doing part in ETA system, which is a Webservice...
So it was needed to replcae some characters form XML data.

We have done this before sevaral time inside some methods...

But this time as the best practice i write a simple method to
do this...

hope it might useful to you:

Character Reference
&
&amp;
<
&lt;
>
&gt;
"
&quot;
'
&apos;



import java.text.CharacterIterator;
import java.text.StringCharacterIterator;



public class EscapeCharacter {
  
  public static void main(String[] args) {

        String str = "sdas\\d\\asa-&-adas-&-das-<-da->-sa";
        System.out.println(str);
      
        
        System.out.println(forXML(str));

    }

    public static String forXML(String aText) {
        aText = aText.replaceAll("&(?!amp;)", "&");
        final StringBuilder result = new StringBuilder();
        final StringCharacterIterator iterator =  new StringCharacterIterator(aText);
        char character = iterator.current();
        while (character != CharacterIterator.DONE) {
            if (character == '<') {
                result.append("<");
            } else if (character == '>') {
                result.append(">");
            } else if (character == '\"') {
                result.append(""");
            } else if (character == '\'') {
                result.append("'");
            } else {
                //the char is not a special one
                //add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        
        return result.toString();
    }


}

No comments:

Some Popular Posts