using javascript to create an xml table correctly

Instead of grabbing all elements in the beginning, I’d suggest just selecting the orders, and looping through their children by selecting them inside the loop:

var orders = xmlDoc.getElementsByTagName('order');

for(i=0; i<orders.length; i++) {
  var order = orders[i];
  var customerid = order.children[0];
  var status = order.children[1];
  var item = order.children[2];

  var name = item.children[0];
  var price = item.children[1];
  var qty = item.children[2];
}

If you don’t know if the children will be in that order, use getElementsByTagName:

for(i=0; i<orders.length; i++) {
  var order = orders[i];
  var customerid = order.getElementsByTagName('customerid')[0];
  var status = order.getElementsByTagName('status')[0];
  var item = order.getElementsByTagName('item')[0];

  var name = item.getElementsByTagName('name')[0];
  var price = item.getElementsByTagName('price')[0];
  var qty = item.getElementsByTagName('qty')[0];
}

Note: use lower cased variable names, since title case is used for classes

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top