Created
December 13, 2017 12:20
-
-
Save stokito/dd0666e6b13870d79bf9de40d8d04e88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("<"); | |
} else if (character == '>') { | |
result.append(">"); | |
} else if (character == '&') { | |
result.append("&"); | |
} else if (character == '\"') { | |
result.append("""); | |
} else if (character == '\'') { | |
result.append("'"); | |
} 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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'< cadabra"> &"; | |
assertEquals(expected, result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment