leosole
leosole

Reputation: 341

python ElementTree XML iteration

I have a xml file structured like so:

<fcd-export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/fcd_file.xsd">
<timestep time="28800.00">
</timestep>
<timestep time="28801.00">
    <vehicle id="301614_485_0" x="13944.12" y="13808.84" angle="276.89" type="pkw" speed="0.00" pos="4.40" lane="23914010#0_0" slope="0.00"/>
</timestep>
<timestep time="28802.00">
    <vehicle id="301614_485_0" x="13942.45" y="13809.04" angle="276.89" type="pkw" speed="2.01" pos="6.41" lane="23914010#0_0" slope="0.00"/>
</timestep>
<timestep time="28803.00">
    <vehicle id="302675_485_0" x="14013.72" y="12670.03" angle="172.02" type="pkw" speed="0.00" pos="4.40" lane="51827455#5_0" slope="0.00"/>
    <vehicle id="301614_485_0" x="13939.51" y="13809.40" angle="276.89" type="pkw" speed="3.55" pos="9.96" lane="23914010#0_0" slope="0.00"/>
</timestep> ...

I have to create timestep objects with a list of vehicles inside:

traces = [] # list with traces
tree = ET.parse(traceFile)
root = tree.getroot()
timeID = 0
for second in root.iter('timestep'):
    traces.append(Time(float(second.get('time'))))
    if not second:
        print("timestep empty")
    else:
        for car in second.iter('vehicle'):
            traces[timeID].cars.append(Car(car.get('id'), float(car.get('x')), float(car.get('y'))))
    timeID += 1
return traces

But that isn't working. After creating a timestep object, it's iterating through the whole file, instead of just the vehicles inside it.

Time and Car are classes I created

class Car:
def __init__(self, id, x, y):
    self.id = id
    self.x = x
    self.y = y

class Time:
def __init__(self, sec):
    self.sec = sec
cars = []
def countCars(self):
    return len(self.cars)

Upvotes: 0

Views: 44

Answers (1)

Oliver.R
Oliver.R

Reputation: 1368

Your issue is that your cars arttribute of your Time class is connected to the class itself, rather than an instance of the class. As such, all of your Time classes share the same cars list, and append to and present this same list.

If you move your cars = [] instantiation inside your __init__() function, and change it to self.cars = [], it should resolve your issue.

class Time:
    def __init__(self, sec):
        self.sec = sec
        self.cars = []

    def countCars(self):
        return len(self.cars)

Upvotes: 1

Related Questions