import xml.etree.ElementTree as ET import argparse import sys def unicode_to_vcf_str(unicode_str): if type(unicode_str) == type(None): return '' hex_list = ['=' + i.encode('hex').upper() for i in unicode_str.encode('utf-8')] return ''.join(hex_list) def main(argv): parser = argparse.ArgumentParser() parser.add_argument('input_file', help='xml file to parse') parser.add_argument('-o', '--output-file', help='vcf output file', default='output.vcf') args = parser.parse_args() tree = ET.parse(args.input_file) contact_records = tree.getroot() with open(args.output_file, 'wb') as output: for contact in contact_records: display_name = unicode_to_vcf_str(contact.find('structuredName').find('displayName').text) phone_number = contact.find('phones').find('phone').find('number').text output.write('BEGIN:VCARD\n') output.write('VERSION:2.1\n') if display_name: output.write('FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:{0}\n'.format(display_name)) if phone_number: output.write('TEL;CELL:{0}\n'.format(phone_number)) output.write('END:VCARD\n') if __name__ == '__main__': main(sys.argv)