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