Saturday, 18 October 2014

Using A JavaScript Array To Hold XML Data



I am trying to use a JavaScript array to hold some XML:



if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{ // IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","movies.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

<!-- Organise the retrieved XML -->
x = xmlDoc.getElementsByTagName("movie");

var name = [];
var name2;

for (i = 0; i < x.length; i++) <!-- loop through the xml file -->
{
name[i] = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue; <!-- get the name -->
name2 = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue; <!-- get the name -->
alert(i + ": " + name[i]);
alert(i + ": " + name2);
}


While the name2 variable works fine and stores the name tags from the XML file, everything in the name array remains undefined. Am I using JavaScript array incorrectly or is there some other error I have missed?


Some sample XML data that my JavaScript should retrieve from "movies.xml" is:



<movie_data>
<title>moviedata</title>
<movie id="1">
<first_channel>
<name>Super Great Movie</name>
<start_time>9:00am</start_time>
<end_time>11:00am</end_time>
</sean_channel>
</movie>
<movie id="2">
<second_channel>
<name>Less Entertaining Movie</name>
<start_time>9:00am</start_time>
<end_time>11:30am</end_time>
</roger_channel>
</movie>
</movie_data>

No comments:

Post a Comment