How to serialize/ make class for XML returned by API
Update you class to:
class VehicleActivity {
VehicleActivity({
this.recordedAtTime,
this.itemIdentifier,
this.validUntilTime,
this.latitude,
});
DateTime? recordedAtTime;
String? itemIdentifier;
DateTime? validUntilTime;
double? latitude;
factory VehicleActivity.fromElement(XmlElement vaElement) => VehicleActivity(
recordedAtTime: DateTime.parse(
vaElement.findElements('RecordedAtTime').first.text,
),
itemIdentifier: vaElement.findElements('ItemIdentifier').first.text,
validUntilTime: DateTime.parse(
vaElement.findElements('ValidUntilTime').first.text,
),
latitude:
double.tryParse(vaElement.findAllElements('Latitude').first.text),
);
}
Notice that you need to use findAllElements
because Latitude
is inside a tag <VehicleLocation>
. Equally, you could find the VehicleLocation
tag and then find the lat/long tags inside that.
I think it would help you to visualise the data better if you format the XML (say in your IDE or browser) to indent it in the traditional way.
<VehicleActivity>
<RecordedAtTime>2021-12-03T18:10:01+00:00</RecordedAtTime>
<ItemIdentifier>ad2c7031-ceac-4e7c-bc0c-9e667ad00dfe</ItemIdentifier>
<ValidUntilTime>2021-12-03T18:16:05.408968</ValidUntilTime>
<MonitoredVehicleJourney>
<LineRef>4</LineRef>
<DirectionRef>inbound</DirectionRef>
<FramedVehicleJourneyRef>
<DataFrameRef>2021-12-03</DataFrameRef>
<DatedVehicleJourneyRef>4_20211203_18_04</DatedVehicleJourneyRef>
</FramedVehicleJourneyRef>
<PublishedLineName>4</PublishedLineName>
<OperatorRef>FTVA</OperatorRef>
<DestinationRef>03700324</DestinationRef>
<VehicleLocation>
<Longitude>-0.719601</Longitude>
<Latitude>51.520305</Latitude>
</VehicleLocation>
<Bearing>30.0</Bearing>
<BlockRef>801312</BlockRef>
<VehicleRef>69921</VehicleRef>
</MonitoredVehicleJourney>