CharSequence (@NotNull CharSequence invalidXml) { if (!hasInvalidAttribute(invalidXml)) { return invalidXml; } // We assume that XML has single- and double-quote characters only for attribute values, therefore we don't any complex parsing, // just have binary inAttribute state StringBuilder buf = new StringBuilder(invalidXml.length()); boolean inAttribute = false; for (int i = 0; i < invalidXml.length(); i++) { char c = invalidXml.charAt(i); if (inAttribute && c == '<') { buf.append("&lt;"); } else if (inAttribute && c == '>') { buf.append("&gt;"); } else if (c == '\"' || c == '\'') { buf.append('\"'); inAttribute = !inAttribute; } else { buf.append(c); } } return buf; }