class HerdCharacterEscapeHandler implements CharacterEscapeHandler {

    @Override
    public void escape(char[] buffer, int start, int length, boolean isAttributeValue, Writer outputWriter) throws IOException
    {
        // Loop through all characters in the buffer starting at "start" and going until the length has been reached.
        for (int i = start; i < start + length; i++)
        {
            // Grab a character in the buffer.
            char ch = buffer[i];

            // Handle the standard XML tag escaping.
            if (ch == '&')
            {
                outputWriter.write("&amp;");
                continue;
            }
            if (ch == '<')
            {
                outputWriter.write("&lt;");
                continue;
            }
            if (ch == '>')
            {
                outputWriter.write("&gt;");
                continue;
            }

            // Handle the single and double quote characters when attributes are present.
            if (ch == '"' && isAttributeValue)
            {
                outputWriter.write("&quot;");
                continue;
            }
            if (ch == '\'' && isAttributeValue)
            {
                outputWriter.write("&apos;");
                continue;
            }

            // Escape the character if it's XML 1.1 restricted.
            if (isXml11RestrictedCharacter(ch))
            {
                outputWriter.write("&#x");
                outputWriter.write(Integer.toHexString(ch));
                outputWriter.write(";");
                continue;
            }

            // In all other cases, output the character as is.
            outputWriter.write(ch);
        }
    }

}