--- /dev/null
+package net.jaekl.cfb.util;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class XmlEscape {
+ // The following code adapted from:
+ // http://stackoverflow.com/questions/439298/best-way-to-encode-text-data-for-xml-in-java#439311
+ private final static String ESCAPE_CHARS = "<>&\"\'";
+ private final static List<String> ESCAPE_STRINGS =
+ Collections.unmodifiableList(Arrays.asList(new String[] {"<", ">", "&", """, "'" }));
+
+ //should only use for the content of an attribute or tag
+ public static String toEscaped(String content) {
+ String result = content;
+
+ if ((content != null) && (content.length() > 0)) {
+ boolean modified = false;
+ StringBuilder stringBuilder = new StringBuilder(content.length());
+ for (int i = 0, count = content.length(); i < count; ++i) {
+ String character = content.substring(i, i + 1);
+ int pos = ESCAPE_CHARS.indexOf(character);
+ if (pos > -1) {
+ stringBuilder.append(ESCAPE_STRINGS.get(pos));
+ modified = true;
+ }
+ else {
+ stringBuilder.append(character);
+ }
+ }
+ if (modified) {
+ result = stringBuilder.toString();
+ }
+ }
+
+ return result;
+ }
+}