r = re.compile('[^\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\xFF' +
    '\u0100-\ud7ff\ue000-\ufdcf\ufde0-\ufffd]')

def escapeInvalidXML(string):

    def replacer(m):
        return '<u>' + '%04X' % ord(m.group(0)) + '</u>'
return re.sub(r, replacer, string)
python: escaping non-ascii characters in XML