How do I loop through a XML nodes in javascript?

2020-02-08 17:32发布

I try to loop through XML nodes that consist of users to create en html table on my website

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);
}

the xml look like this

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

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条回答
▲ chillily
2楼-- · 2020-02-08 18:17

One of the least intuitive things about parsing XML 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);
}   
查看更多
登录 后发表回答