def escape_cdata(data, encoding):
    """Escape character data using the given encoding."""
    if '&' in data:
        data = data.replace('&', '&amp;')
    if '<' in data:
        data = data.replace('<', '&lt;')
    if '>' in data:
        data = data.replace('>', '&gt;')
    return data.encode(encoding, 'xmlcharrefreplace')
