0

I have created a loop in JavaScript that reads out the name of my nodes and the value inside.

The loop works for the first node and the second one, but on the rest of the nodes it's just repeating the value of the second node.

So the output gets like this:

 Name on nod 1 is title
 The value in the node is XML Content and Data

 Name on nod 2 is Author
 The value in the node is XML Content and Data

Et cetera.

Should I create a loop inside the loop? Ir can I multiloop the entire tree?

if (xmlDoc.parseError != 0) {
    alert("Error Code: " + xmlDoc.parseError.errorCode + "\n"
        + "Error Reason: " + xmlDoc.parseError.reason + "\n"
        + "Error Line: " + xmlDoc.parseError.line)
}
root = xmlDoc.documentElement
rootList = root.childNodes
len = rootList.length

x = xmlDoc.getElementsByTagName("title")[0]
y = x.childNodes[0];

for (i = 0; i < len; i++) {
    j = i + 1
    document.write("Name on nod " + j + " is " + rootList.item(i).nodeName + "<br />")
    document.write(" value of the the nod is  " + y.nodeValue + "<br />" + "<br />");
}
Community
  • 1
  • 1
Dymond
  • 2,158
  • 7
  • 45
  • 80
  • 1
    A loop within a loop.... "We need to go deeper!" :-P – Quasdunk Jan 16 '12 at 22:36
  • i think you are looking for recursive functions http://javascript.about.com/library/blrecursive.htm – Hector Sanchez Jan 16 '12 at 22:37
  • If it would make it any ezier, I have a php lib (dun really remember where i got it, as I had to tweak it some to make it 100% effective and go deeper into xmls with multiple children). But it makes getting an xml as an array EZ then you can just use "echo json_encode(theArray);" to send it to your js as an object, then all you have to do is loop through the object and setup what you need. It is 100x easier than trying to manually parse an XML in js. just let me know if you want the lib and i'll be happy to post it somewhere or email it to ya. – SpYk3HH Jan 16 '12 at 22:42

2 Answers2

1

y is always pointing to the same node (y= x.childNodes[0]). You probably intend to get a different node in each iteration of the loop.

Sebastian
  • 2,249
  • 17
  • 20
  • Exactly what Im in to, but Im completely new at this so ever step takes about an hour for me :) – Dymond Jan 16 '12 at 23:28
0

Log value of i in the loop. If you see it repeating then JavaScript for loop index strangeness can probably help you.

Community
  • 1
  • 1
Aman
  • 153
  • 6