Skip to content

Instantly share code, notes, and snippets.

@stokito
Created December 13, 2017 12:20
Show Gist options
  • Save stokito/dd0666e6b13870d79bf9de40d8d04e88 to your computer and use it in GitHub Desktop.
Save stokito/dd0666e6b13870d79bf9de40d8d04e88 to your computer and use it in GitHub Desktop.
package util;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class XMLEscaper {
public static final String[] ESCAPED_CHAR = {"&", "'", "\"", "<", ">"};
public String escape(String aText) {
if (aText == null) return null;
StringBuilder result = new StringBuilder();
StringCharacterIterator iterator = new StringCharacterIterator(aText);
char character = iterator.current();
while (character != CharacterIterator.DONE) {
if (character == '<') {
result.append("&lt;");
} else if (character == '>') {
result.append("&gt;");
} else if (character == '&') {
result.append("&amp;");
} else if (character == '\"') {
result.append("&quot;");
} else if (character == '\'') {
result.append("&apos;");
} else {
result.append(character);
}
character = iterator.next();
}
return result.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("List of escaped characters: ");
for (String escChar : ESCAPED_CHAR) {
sb.append(escChar).append(" ");
}
return sb.toString();
}
}
package util;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class XMLEscaperTest {
private XMLEscaper testInstance;
@Before
public void setUp() {
testInstance = new XMLEscaper();
}
@Test
public final void escape() {
String test = "abra\'< cadabra\"> &";
String result = testInstance.escape(test);
String expected = "abra&apos;&lt; cadabra&quot;&gt; &amp;";
assertEquals(expected, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment