PDA

View Full Version : Loop through XML using Javascript



daily_matters
01-21-2010, 04:27 PM
Hi everyone, i'm new to this forum, and i started developing web appications little time ago. I Have a doubt here, so maybe someone can help me.

I'm having problems trying to loop through a XML file using javascript.
Here's my xml:



<ORGANIZER>
<TODO>
<QUEM>Antonio</QUEM>
<OQUE>Ir buscar os pro-forma</OQUE>
<COMENTARIOS>Urgente</COMENTARIOS>
</TODO>

<TODO>
<QUEM>Antonio</QUEM>
<OQUE>Mandar sms</OQUE>
<COMENTARIOS>… a minha vida !</COMENTARIOS>
</TODO>
</ORGANIZER>


I can do it so it shows the first <TODO> information, but i don't know how to do it so it shows all the info in the XML file. I tried looping through it using for loops, but i still can't. I know it's not a very difficult thing, but i'm not seeing it. Here's my java script:


function displayTodo(){
for(j=0;j<=todo.length; j++){
who=(y[j].getElementsByTagName("QUEM")[0].childNodes[0].nodeValue);
what=(y[j].getElementsByTagName("OQUE")[0].childNodes[0].nodeValue);
why=(y[j].getElementsByTagName("COMENTARIOS")[0].childNodes[0].nodeValue);

txt= "<p><b>" + who + "</b> : " + what + " <b>Notas a considerar:</b> " + why + "</p>";

document.getElementById("todo").innerHTML=txt;
}
}


That for cycle it's not working... Can anybody help me ???

Thx in advance, ClŠudio

harrierdh
01-21-2010, 07:15 PM
try changing this

for(j=0;j<=todo.length; j++){

to this

for(j=0;j<todo.length; j++){

daily_matters
01-21-2010, 07:19 PM
Currently i have this code:


function displayTodo(){
for(j=0; j<y.length;j++){
who=(y[j].getElementsByTagName("QUEM")[0].childNodes[0].nodeValue);
what=(y[j].getElementsByTagName("OQUE")[0].childNodes[0].nodeValue);
why=(y[j].getElementsByTagName("COMENTARIOS")[0].childNodes[0].nodeValue);

txt= "<p><b>" + who + "</b> : " + what + " <b>Notas a considerar:</b> " + why + "</p>";

document.getElementById("todo").innerHTML=txt;
}
}

It's cycling through the code but it's only showing the last result. Now i want to make it display all the results, any ideas on how to do that ?

Dormilich
01-21-2010, 07:34 PM
try

document.getElementById("todo").innerHTML += txt;
otherwise innerHTML is overwritten in every cycle.

there is also room to optimize the code

function displayTodo()
{
// define your local variables, otherwise they are global (and we all know, globals are evil)
// define todo, y inside!
var j, l = todo.length, who, what, why, el;
// do as less DOM accesses as possible
el = document.getElementById("todo");
for (j = 0; j < l; j++) {
// textContent is part of DOM level 3
who = y[j].childNodes[0].textContent; // if <QUEM> is always the first node
what = y[j].childNodes[1].textContent; // if <OQUE> is always the second node
why = y[j].childNodes[2].textContent; // if <COMMENTARIOS> is always the third node
el.innerHTML += "<p><b>" + who + "</b> : " + what + " <b>Notas a considerar:</b> " + why + "</p>";
}
}