15

I'm trying to loop through XML nodes containing information about users to create an HTML table on my website.

This is what the XML looks like:

<websites_name>
<user>...</user>
<user>...</user>
.
.
.
</websites_name>

And this is the code I'm trying to parse it with:

for(var user in xmlhttp.getElementsByTagName('user')){   //fix this row to me
    //Create a new row for tbody
    var tr = document.createElement('tr');
    document.getElementById('tbody').appendChild(tr);
}

UPDATE

xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","some URL",true);
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var root = xmlDoc.getElementsByTagName('websites_name');
for(var i=0, i<root[0].childNodes.length,i++){
    //Create a new row for tbody
    var tr = document.createElement('tr');
    document.getElementById('tbody').appendChild(tr);
}

1 Answer 1

21

One of the least intuitive things about parsing XML in JavaScript is that the text inside the element tags is actually a node you have to traverse into.

Assuming it's <user>text data</user>, you not only have to traverse into the text node of the user element to extract your text data, but you have to create a text node with that data in the DOM to see it. See nodeValue and and createtextnode:

// get XML 
var xml = xhr.responseXML;

// get users
var users = xml.getElementsByTagName("user");
for (var i = 0; i < users.length; i++) {   
    var user = users[i].firstChild.nodeValue;
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    var textNode = document.createTextNode(user);
    td.appendChild(textNode);        
    tr.appendChild(td);        
    document.getElementById("tbody").appendChild(tr);
}   
Sign up to request clarification or add additional context in comments.

3 Comments

I've located the problem it lies in the row "var root = xmlDoc.getElementsByTagName("websites_name");".What have I done wrong? Look at my update. Your solution is the same except for the textNode. It is actually mor XML nodes under user
ok I know what the problem was. A very minor. The scripts that produced my XML , I forgot the row "header("Content-type: text/xml");"
awesome - yeah, that content type stuff is super important with ajax. this stuff is a lot easier with libraries like jquery ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.