开发者

XML loop collecting too many element in array

Hey guys I'm having trouble looping through some XML. Im trying to capture the elements and use them as js variables. 开发者_开发问答My XML is.

<box>
 <thing>
          <id>5</id>
          <numbers>
              <number>4</number>
              <number>6</number>
          </numbers>
 </thing>
 <thing>
          <id>2</id>
          <numbers>
              <number>8</number>
              <number>5</number>
              <number>9</number>            
          </numbers>
 </thing>
 <thing>
          <id>88</id>
          <numbers>
              <number>78</number>
          </numbers>
 </thing>
 </box>

My JS.

ajax(site, params)

var things =  xmlDoc.getElementsByTagName("thing");

for (i=0; i<things.length; i++){
    var id = things[i].getElementsByTagName("id")[0].firstChild.nodeValue;
    var numbers =  things[i].getElementsByTagName("numbers");
    var value;
    for (n=0; n<numbers.length; n++){
        var number = numbers[n].getElementsByTagName("number");
        value = value + number;
    }

    id = value;
 }

The problem I'm having is that when I grab the elements it seems to grab all the elements from the entire page.

And adds them to value so I end up with

id #1 = 110;
id #2 = 100;
id #3 = 78;

Is there another way to achieve what I am trying to do here?


How about something like this

for (var i = 0; i < things.length; i++) {
    var thing = things[i];
    var id = thing.getElementsByTagName('id')[0].firstChild.nodeValue;
    var numbers = thing.getElementsByTagName('number');
    for (var j = 0, value = 0; j < numbers.length; j++) {
        value += numbers[j].firstChild.nodeValue;
    }
    console.log(id, value);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜