/** * Converts the given attribute value to an XML-text-safe value, meaning that * less than and ampersand characters are escaped. * * @param textValue the text value to be escaped * @return the escaped value */ @NonNull public static String toXmlTextValue(@NonNull String textValue) { for (int i = 0, n = textValue.length(); i < n; i++) { char c = textValue.charAt(i); if (c == '<' || c == '&') { StringBuilder sb = new StringBuilder(2 * textValue.length()); appendXmlTextValue(sb, textValue); return sb.toString(); } }
return textValue; }
/** * Appends text to the given {@link StringBuilder} and escapes it as required for a DOM text * node. * * @param sb the string builder * @param start the starting offset in the text string * @param end the ending offset in the text string * @param textValue the text value to be appended and escaped */ public static void appendXmlTextValue( @NonNull StringBuilder sb, @NonNull String textValue, int start, int end) { for (int i = start, n = Math.min(textValue.length(), end); i < n; i++) { char c = textValue.charAt(i); if (c == '<') { sb.append(LT_ENTITY); } else if (c == '&') { sb.append(AMP_ENTITY); } else { sb.append(c); } } }