import six


def encode_ascii_xml(x):
    """Encode a string as fixed-length 7-bit ASCII with XML-encoding
    for characters outside of 7-bit ASCII.

    Respect python2 and python3, either unicode or binary.
    """
    if isinstance(x, six.text_type):
        return x.encode('ascii', 'xmlcharrefreplace')
    elif isinstance(x, six.binary_type):
        return x
    else:
        raise ValueError('Expected string type, got type %s' % str(type(x)))