Some of the XML nodes is not always present in the XML feed, like gate and status, causing my code to break. This is my code:
$( document ).ready(function() {
$('#load_btn').click(function() {
loadXMLDoc();
});
});
function loadXMLDoc() {
$.ajax({
url: "proxy.php",
type: "POST",
dataType: "xml",
data: {
address: "http://flydata.avinor.no/XmlFeed.asp?TimeFrom=1&TimeTo=7&airport=OSL&direction=D&lastUpdate=2016-04-12T15:03:00Z"
},
})
.done(function (xml) {
var flightXML = $(xml).find('flight');
//console.log(flightXML);
var output = "<table>";
output += "<tr><th>Departue</th><th>Flight</th><th>To</th><th>Airline</th><th>Gate</th></tr>"
for(i=0; i < flightXML.length; i++)
{
var line = "<tr>";
var timeElement = flightXML[i].getElementsByTagName("schedule_time");
var time = timeElement[0].firstChild.nodeValue;
var idElement = flightXML[i].getElementsByTagName("flight_id");
var id = idElement[0].firstChild.nodeValue;
var toElement = flightXML[i].getElementsByTagName("airport");
var to = toElement[0].firstChild.nodeValue;
var airlineElement = flightXML[i].getElementsByTagName("airline");
var airline = airlineElement[0].firstChild.nodeValue;
var gateElement = flightXML[i].getElementsByTagName("gate");
var gate = gateElement[0].firstChild.nodeValue;
//var statusElement = flightXML[i].getElementsByTagName("status");
//var status = statusElement[0].firstChild.nodeValue;
line += "<td>" + time + "</td><td>" + id + "</td><td>" + to + "</td><td>" + airline + "</td><td>" + gate + "</td>";
line += "</tr>";
output += line;
}
output += "</table>";
document.getElementById("result").innerHTML = output;
});
}
This is the XML structure:
<flight uniqueID="5819145">
<airline>SK</airline>
<flight_id>SK815</flight_id>
<dom_int>I</dom_int>
<schedule_time>2016-04-12T18:15:00Z</schedule_time>
<arr_dep>D</arr_dep>
<airport>LHR</airport>
<check_in>7 8</check_in>
<gate>F19</gate>
</flight>
<flight uniqueID="5818372">
<airline>EW</airline>
<flight_id>EW4197</flight_id>
<dom_int>S</dom_int>
<schedule_time>2016-04-12T18:15:00Z</schedule_time>
<arr_dep>D</arr_dep>
<airport>HAM</airport>
<check_in>7</check_in>
<status code="C"></status>
</flight>
<flight uniqueID="5818645">
<airline>SK</airline>
<flight_id>SK291</flight_id>
<dom_int>D</dom_int>
<schedule_time>2016-04-12T18:15:00Z</schedule_time>
<arr_dep>D</arr_dep>
<airport>BGO</airport>
<check_in>7 8</check_in>
<gate>A4</gate>
</flight>
How can I check for presence of these nodes, and if not present, insert a blank space (or whatever is needed for my code not to break)?