Example #1
0
def create_xml():
    """
    Create an XML file
    """

    xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <root>
    </root>
    '''

    root = objectify.fromstring(xml)
    print os.name
    if os.name == 'posix':
        str_name = '/Users/haroldkurth/Library/Mobile Documents/com~apple~CloudDocs/RideSystems/Source/google_transit/stop_times.txt'
    else:
        str_name = 'C:/Users/hkurth1348/iCloudDrive/RideSystems/Source/google_transit/stop_times.txt'
    name = raw_input("Enter file:")
    if len(name) < 1:
        name = str_name
    handle = open(name)
    current_group = None
    for line in handle:
        line = line.rstrip('\r\n')
        words = line.split(',')
        trip_id = words[0]
        arrival_time = words[1]
        departure_time = words[2]
        stop_id = words[3]
        stop_sequence = words[4]
        stop_headsign = words[5]
        pickup_type = words[6]
        dropoff_type = words[7]
        shape_dist_traveled = words[8]
        if trip_id == 'trip_id':
            continue
        my_trip = root.findall(".//*[@name='root']/trip")
        result = 0
        if current_group is None or trip_id != current_group.get('name'):
            # Start a new group
            current_group = objectify.SubElement(root, 'trip', name=trip_id, text=trip_id)
        # for child in my_trip:
        #     if child.find('trip_id').text == str(trip_id):
        #         result = 1
        # if result == 0:
        #     # add_string(root, ['T'+trip_id, ''], '')
        #     b = objectify.SubElement(root, 'trip', name=trip_id)
        b = current_group
        add_string(b, ['Seq_'+stop_sequence, 'trip_id'], trip_id)
        add_string(b, ['Seq_'+stop_sequence, 'stop_sequence'], stop_sequence)
        add_string(b, ['Seq_'+stop_sequence, 'arrival_time'], arrival_time)
        add_string(b, ['Seq_'+stop_sequence, 'departure_time'], departure_time)
        print trip_id, stop_sequence

    # remove lxml annotation
    objectify.deannotate(root)
    ElementTree.cleanup_namespaces(root)

    # create the xml string
    obj_xml = ElementTree.tostring(root,
                             pretty_print=True,
                             xml_declaration=True)

    try:
        with open("stop_times.xml", "wb") as xml_writer:
            xml_writer.write(obj_xml)
    except IOError:
        pass