How do I loop through a XML nodes in javascript?

后端 未结 1 1626
清酒与你
清酒与你 2020-12-14 22:01

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          


        
1条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 22:46

    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 text data, 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);
    }   
    

    0 讨论(0)
提交回复
热议问题