View Full Version : XML to JavaScript array - undefined elements

11-07-2006, 09:49 PM

I'm developing a web application that imports an XML file, and writes the nodes to an array. I can successfully import my XML file and traverse the nodetree.

I want to write the nodes to a JavaScript array. When I write the nodes to array elements, my script is including an element for parent nodes that have children but no value. This is recorded as an "undefined" array element, which I want to skip. Here's a simplified example:


function processProductmaster(xmlDoc) {
var x = xmlDoc.getElementsByTagName('item'); // The imported XML
var productArray = new Array();
for (i=0;i<x.length;i++) {
productArray[i] = new Array();
for (j=0;j<x[i].childNodes.length;j++) {
if (x[i].childNodes[j].nodeType != 1) continue; //Skip if it's not an element
var theObj = x[i].childNodes[j].firstChild.nodeValue;
productArray[i][j] = theObj;

The results
undefined, 1, Sample1, 2.3

I have tried identifying the "undefined" values like this:
if (x[i].childNodes[j].firstChild.nodeValue == null)
if (x[i].childNodes[j].firstChild.nodeValue == "undefined")
but in spite of the fact that the array element appears empty, there must be *something* inside them, because neither of these checks can spot it.