def autoDetectXMLEncoding(buffer):
 encoding = 'utf_8'
 if (len(buffer) >= 4):
  bytes = (byte1, byte2, byte3, byte4) = tuple(map(ord, buffer[0:4]))
  enc_info = autodetect_dict.get(bytes, None)
  if (not enc_info):
   bytes = (byte1, byte2, None, None)
   enc_info = autodetect_dict.get(bytes)
 else:
  enc_info = None
 if enc_info:
  encoding = enc_info
  secret_decoder_ring = codecs.lookup(encoding)[1]
  (decoded, length) = secret_decoder_ring(buffer)
  first_line = decoded.split('\n')[0]
  if (first_line and first_line.startswith(u'<?xml')):
   encoding_pos = first_line.find(u'encoding')
   if (encoding_pos != (-1)):
    quote_pos = first_line.find('"', encoding_pos)
    if (quote_pos == (-1)):
     quote_pos = first_line.find("'", encoding_pos)
    if (quote_pos > (-1)):
     (quote_char, rest) = (first_line[quote_pos], first_line[(quote_pos + 1):])
     encoding = rest[:rest.find(quote_char)]
 return encoding

def autoDetectXMLEncoding ( buffer ) : encoding = 'utf_8' if ( len ( buffer ) >= 4 ) : bytes = ( byte1 , byte2 , byte3 , byte4 ) = tuple ( map ( ord , buffer [ 0 : 4 ] ) ) enc_info = autodetect_dict . get ( bytes , None ) if ( not enc_info ) : bytes = ( byte1 , byte2 , None , None ) enc_info = autodetect_dict . get ( bytes ) else : enc_info = None if enc_info : encoding = enc_info secret_decoder_ring = codecs . lookup ( encoding ) [ 1 ] ( decoded , length ) = secret_decoder_ring ( buffer ) first_line = decoded . split ( '\n' ) [ 0 ] if ( first_line and first_line . startswith ( u'<?xml' ) ) : encoding_pos = first_line . find ( u'encoding' ) if ( encoding_pos != ( - 1 ) ) : quote_pos = first_line . find ( '"' , encoding_pos ) if ( quote_pos == ( - 1 ) ) : quote_pos = first_line . find ( "'" , encoding_pos ) if ( quote_pos > ( - 1 ) ) : ( quote_char , rest ) = ( first_line [ quote_pos ] , first_line [ ( quote_pos + 1 ) : ] ) encoding = rest [ : rest . find ( quote_char ) ] return encoding
buffer -> encoding_name the buffer should be at least 4 bytes long .