def safe_xml_str(s, use_encoding='utf-8'):
 illegal_xml = re.compile(u'[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]')
 if (not isinstance(s, unicode)):
  if isinstance(s, str):
   s = unicode(s, use_encoding, errors='replace')
  else:
   s = unicode(s)
 s = illegal_xml.sub(u'\ufffd', s)
 return s

def safe_xml_str ( s , use_encoding = 'utf-8' ) : illegal_xml = re . compile ( u'[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]' ) if ( not isinstance ( s , unicode ) ) : if isinstance ( s , str ) : s = unicode ( s , use_encoding , errors = 'replace' ) else : s = unicode ( s ) s = illegal_xml . sub ( u'\ufffd' , s ) return s
replace invalid-in-xml unicode control characters with ufffd .