X-Git-Url: http://jaekl.net/gitweb/?p=cfb.git;a=blobdiff_plain;f=prod%2Fnet%2Fjaekl%2Fcfb%2Futil%2FXmlEscape.java;fp=prod%2Fnet%2Fjaekl%2Fcfb%2Futil%2FXmlEscape.java;h=9e177bbd9a9b0bbca87ea91647dd418fcecdc6f7;hp=0000000000000000000000000000000000000000;hb=e9a80ba4b35ce25d00d259038c7d2cb0a954dcc4;hpb=4b7b597ce11de6d85ac77c089e1eb7ca0cb30f66 diff --git a/prod/net/jaekl/cfb/util/XmlEscape.java b/prod/net/jaekl/cfb/util/XmlEscape.java new file mode 100644 index 0000000..9e177bb --- /dev/null +++ b/prod/net/jaekl/cfb/util/XmlEscape.java @@ -0,0 +1,39 @@ +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 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; + } +}