0

I have XMl simulation output, with many vehicle lines like:

    <routes>
        <vehicle id="8643" type="car" depart="0.03" departLane="free" departSpeed="max" fromTaz="63" toTaz="5">
        <vehicle id="8928" type="car" depart="0.34" departLane="free" departSpeed="max" fromTaz="663" toTaz="1147">
    </routes>

Currently I have the below which prints the required attributes.

import xml.etree.cElementTree as ET
e = ET.parse('trip_049.rou.xml')
root = e.getroot()

for vehicle in root.findall('vehicle'):
    id = vehicle.get('id')
    origin = vehicle.get('fromTaz')
    destination = vehicle.get('toTaz')
    print id,origin,destination

Which outputs:

8643 63 5
8928 663 1147

But I need the loop output to be stored in a numpy array or equivalent like:

id   origin destination
8643 63     5
8928 663    1147

Thank you in adavance

2
  • do you want them as a 2-d numpy array? And you want the elements to be of type string? Commented Sep 9, 2015 at 15:38
  • yes 2-d; for the elements in the example type integers, but I may have some string elements to add later. I will remove str from the example Commented Sep 9, 2015 at 15:42

1 Answer 1

2

You can simply create a 2-dimensional list, and then at the end convert it to numpy array. Example -

import xml.etree.cElementTree as ET
import numpy as np
e = ET.parse('trip_049.rou.xml')
root = e.getroot()

tdlist = []
for vehicle in root.findall('vehicle'):
    id = vehicle.get('id')
    origin = vehicle.get('fromTaz')
    destination = vehicle.get('toTaz')
    tdlist.append([id,origin,destination])

arraylst = np.array(tdlist)

The elements in tdlist and consequently in arraylst would be of type str . If you want them as integers, then you should convert them to int as -

id = int(vehicle.get('id'))
origin = int(vehicle.get('fromTaz'))
destination = int(vehicle.get('toTaz'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.