Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through XML nodes in JavaScript?

Tags:

javascript

xml

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);
}
like image 845
einstein Avatar asked Dec 06 '10 01:12

einstein


People also ask

What are XML nodes?

Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.

What is traversing the elements and attributes in an XML document called?

A Schema describes the elements and attributes that are valid in an XML document, and the contexts in which they are valid.


Video Answer


1 Answers

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);
}   
like image 182
Myer Avatar answered Sep 16 '22 18:09

Myer