How to loop through XML nodes in javascript?

I am trying to iterate over XML nodes that are composed of users to create an 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); } 

xml is as follows

 <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); } 
+8
javascript xml
source share
1 answer

One of the least intuitive things about parsing XML is that the text inside the element tags is actually the node you have to go through with.

Assuming this is <user>text data</user> , you need to not only go through the node text of the user element to retrieve your text data, but you need to create a node text with that data in the DOM to see it. See nodeValue 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); } 
+12
source share

Source: https://habr.com/ru/post/649854/


All Articles